UPDATE: Hi all, there is a small bug in the CrossHairTarget script which will cause the gun to fire backwards. Convert lines 22/23 to this: if (Physics.Raycast(ray, out hitInfo)) { transform.position = hitInfo.point; } else { transform.position = ray.origin + ray.direction * 1000.0f; }
For those people who have a character close to camera, consider to use layers or tags to ignore the player on raycasts, or every ray cast will be absolute messy. Kiwicoder has a character far from the center of the cam, however, he can face problems when the cam is moving closer to character in some situations like when cam avoid clipping. PD: great tutorials dude (clap!, clap!, clap!)
You are the legend. Honestly, one of the best tutorial channel. The explanations are so clear. Absolutely deserve a lot of subscribers but for now just one more by me :)
For the ones who has a computer freeze after running game, it is happening because of the while loop. Change while( accumulatedTime >= 0) to while( accumulatedTime >= fireInterval). Fixed.
I just finished this video. Your videos on this topic so far have been the best ever on RUclips. Your detailed explanation of the complex content puts some courses on Udemy to shame. If you do a course on Udem, I will be one of the first to buy it. Great content!.
@@nikhstudiosthe1 For those still having issues, make sure you are adding Gizmos to the scene you are actually looking at! If you add the Gizmos in the "Game" scene, look there!
Thank you so much for this tutorial ! I had some troubles as the particles of the pack were different for me, with other settings. But I changed my projectile based shooting system to a hitscan one after seeing your tuto and it fix a lot of issues that I had. I'll just need to watch the 2nd part of the video now to implement some velocity and drop :) Thanks again !
Amazing dude keep up the good work btw thnx for the tutorial series. i have only done game dev for 5 month now and i couldnt really understud c# or programing and i just kept researching and i saw your chanell and i kept following until i finished the series and i looked back at the code and i slowly understud how c# and programing works and then i changed it to an fps and im having with trying to make a game of my so thank you kiwi coder keep up the good work.
Excellent tutorial! I'm amazed at how much the muzzle flash and hit effects add to the realism. I checked a bunch of other comments to see if you had answered this question, so hopefully I'm not making you repeat something. How do you handle raycasting at objects that are really close to the player? I'm using a very similar raycast system from the center of the screen and making my bullets travel from the tip of the gun towards my aim target. If I walk up to an object so that I'm basically touching it, it become very obvious that bullets are shooting almost sideways out of the gun.
Super awesome tutorial once again. took me all day but I got it all working lol. As a request it would be cool to see a state based character controller for like running jumping climbing ladders or walls etc later. or some tutorials on how to equip stuff to your character from like a shop (clothing items/armour etc). Thanks again!
I'm having an issue with my raycast Debug.DrawLine at around 9:55. The line is not appearing. I have added Debug.Log(hitInfo.point) to print the endpoint to the console, which works properly, so the ray is being cast and intersecting with objects. Idk why the DrawLine is not working. Anyone have any suggestions? Edit: Never mind I just didn't have gizmos enabled.
The last part of the video (the part where you mostly do the scripting for bullet drop and bullet simulation) is kinda confusing and you went over it super quickly. It would be helpful to have like a conclusion or an overview of what you were doing (something like a drawing or illustration that explains the logic behind the script). That's just my two cents.
I don't have RaycastWeapon Edit: got it to work. I just don't know how to delete all the instantiated objects Edit2: nevermind, I just didn't see the tutorial fully. Ok now I got everything to work. Thank you for the tutorial :D
Excellent tutorial! I learned a lot from it. Thank you! At 3:28, I noticed you put the input processing code in the LateUpdate method instead of Update method. Are there any good reasons to do that, why not just put the code in Update method?
No, input should be processed as early in the frame as possible. I was probably fighting against a cinemachine update ordering issue with animation rigging
Firstly a huge congrats! It is the best Raycast shoot tutorial I have seen. I am surprised by the so advanced level. How many years are you programming C#?
thanks for the last part. I wasted 2 days finding and thinking how to perform that. although I didn't understand most of the codes for making a lot of functions but things are working for me and I can make the work done by that :D
Hello man! I did follow your tutorial but i can't manage to get my material right for the bullet tacer. It's invisible for me. I do see the fact that it's there whe i select it in my inspector. Have you ever had such an issue? great tutorial btw :)
This is awesome! Thank you so much. I am trying to make an "energy cannon" style weapon that shoots a decent-sized "energy ball" projectile at a slower speed than a bullet would travel. The methods you used seem like they should work for this use-case! Originally I was going to use a rigidbody with a sphere collider and Unity's physics system to calculate travel & hit detection, but I read that this may be performance heavy and a raycast-based projectile is more optimized. I particularly like the equation-based (deterministic) positioning of the bullet based on time. Some questions for you: 1. Why did you use 'LateUpdate' to calculate bullet travel rather than 'Update' or 'FixedUpdate'? I trust that this works, but it wasn't explained in the video. 2. Would it be "wrong" to use 'FixedUpdate' for calculating bullet travel/impact? And what are the implications of doing so? (For example, poor performance?) For #2 I understand that using 'Update' or 'LateUpdate' would always provide smooth visual movement of the bullet (since 'FixedUpdate' time may not always line up with the 'Update' loop, causing jitter). However, I'm second guessing myself because isn't 'FixedUpdate' the right thing to use if we're doing a physics calculation such as a bullet hitting a wall? If we used 'LateUpdate' then wouldn't the accuracy of bullet impact calculations differ based on each player's framerate, putting lower-spec players at a disadvantage? Could a combination of both be used - 'FixedUpdate' for hit detection and 'LateUpdate' for the visual? Or does it actually not matter that much and I am overthinking it? For a competitive multiplayer game I just want to make sure things are accurate *enough*, even if 'LateUpdate' is used.
It’s been a while since I made this but I think I used late update to ensure animation rigging had run and the muzzle position was up to date when spawning the bullet. But you’re right though fixed update sounds better for simulation and use late update for the visuals. For a multiplayer game though you might be running the hit detection on the server which is untied to the clients frame rate.
4 года назад+1
Thanks for the great tutorial. I am learning so much with your videos. You are really awesome. I noticed an issue with the fire rate and have not found a solution to that yet. If i click as fast as i can, i am able to ignore the fire rate of the gun. This is easier to spot when the fire rate is set to a low value (e.g. 5). It has to do with resetting accumulatedTime and FireBullet() in StartFiring(). Since i removed both those line from StartFiring() function i am not able to fire faster than the fire rate, but also some manual shots get ignored because the accumulated time is never reset.
You're welcome! Thanks for spotting that. To fix it: accumulatedTime should be updated even when not firing, so move it into UpdateBullets for example. Then inside StartFiring, check that it is greater than zero before resetting (if it is negative, it's still in the cooldown period).
4 года назад+1
@@TheKiwiCoder Your suggestion works like a charm. Thanks!
@ Maybe u can post this part of code? I got the problem that it looks like i fire 2 Bullets in a row and i mean it have something to do with the accumulated time and firerate.... would be very nice men ^^ ( also happend on pistol with fireRate of 1 -> always shot 2 bullets.)
Brilliant video - again! How do I change the rotation of the gun at this point? It's not quite pointing at the target dot when I aim. I can't find a way of doing it now everything is hooked up. Thanks
@@TheKiwiCoder Thanks for that but it doesn't seem to do much. I'd like to change the position of the gun in the hands but now the aiming system is working I can't do it when in play mode as I can't aim and adjust settings at the same time. I can't temporarily turn off things either so I can reposition my gun and hands. When in play mode I can't see my gun as it's behind the player - I'd like to move it if possible. Any thoughts would be welcome -thanks again - brilliant tutorials
Ah ok, what you can do is rather than aiming the weapon, create a weapon holder object, and add the weapon as a child of that. Attach a rig constraint to it which you can then position. It’s explained a bit more in this video: ruclips.net/video/bIOxl8iDWoU/видео.html
This is a great video. I found that I had to test that bullet.tracer wasn't null in RaycastSegment. Weirdly the video stutters for me. 1080p60. No other makers videos do. Strange. Doesn't take away from the video though. Thanks ☺
Maybe use layers to ignore the player / whatever is in the way, also i was using projectile prefabs instead of raycast, that way you need to normalize the direction vector, otherwise it gets faster the further the crosshair target is from the gun
Absolutely love this solution, and the steps were really well explained! I do have one question, about the ray section function. You make a raycast from the start point, in the direction of and distance to the end point. Are there any advantages to this, compared to a linecast from start to end?
i couldnt make the material of the trail cuz i didnt find the same values to change can u upload the material ? i mean the material of the bullet tracer thanks for the tutorial it was helpful
Never mind, fixed it! The FireBullet() call in StartFiring was happening at the exact same time as when UpdateFiring would call it as well. Just removed the reference in StartFiring and now I'm shooting one bullet when I first click. It's been a few weeks since I last watched this video so maybe I missed a bit where you addressed this.
Hey @TheKiwiCoder! I was just wondering, do your bullets also persist (dont get destroyed) when you aim and fire at horizon? I notice in the code that the maxLifetime of the bullet is only set OnHit, but not in the else statement. Awesome tutorial vids my man! Keep it up!
@TheKiwiCoder Hey man, having a small issue. If I move my character little by little the animation pose becomes warped until my normal holding the gun pose looks like broken wrists and physics from a world Doctor Strange frequents. It starts off behaving perfectly, but maybe bleeding kinematics causing pose warping? (The subtle inaccuracies adding up over hundreds of tiny movements until the referenced transforms resemble nothing of the initial values) I'm not sure but I'm at a loss. Did you or anyone else here experience anything like this?
I would change a combination of FOV and zoffset. Another thing to experiment with is creating a separate dedicated camera and blend between them using cinemachine
There is a problem I'm having that if I point the gun towards the sky, there are no tracers. the reason for that is because hit.point is null so when the raycast doesn't hit anything then the trail is not seen. please help
I saw these videos back in the day now i was working on a Shooting game ran into the same issue about crosshair. I was thinking about the solution. Then i remembered there was a Legend "TheKiwiCoder" who posted the solution about same issue
How would you make an object pool out of the bullets? This instantiates and destroys objects constantly which isn't optimal. I am having some issues with trying to modify your script to be able to use object pooling
This might help: docs.unity3d.com/2021.1/Documentation/ScriptReference/Pool.ObjectPool_1.html Replace new Bullet with pool.Get(), and call pool.Release() on the bullet before removing it from the list.
Sir.... I upgraded along this video. but i met big problem. All world changed pink color. material destroy error. What can i solve this problem? please sir........
Hey, upgrading materials should fix the pink materials. Check the shader on the material is set to ‘Urp/lit’ shader. There are other videos on RUclips about this topic that should help. Good luck!
carrot if you’re using synty studios asset pack you might want to check their RUclips tutorial on how to obtain their latest URP compatible materials. Sci fi city pack which is used in this video series has been upgraded.
I know this is old, but I just ran into this problem. In case anyone else does too, I am posting the solution I found. First follow this docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.3/manual/InstallURPIntoAProject.html Then this docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.3/manual/upgrading-your-shaders.html My terrain was still pink so I just made a new one. Idk if there is a better way.
I really like your teaching style I get why you writing the code you are, not just following along. But I have found a bug and haven't found the solution in the comment section: Basically whenever the player fires with the crosshair on something behind the character (perhaps the character is running under a bridge) it shoots backward towards where the crosshair is placed. I know it is down to the ray destination being where ever the cross-hair is (in the above example that location would momentarily be the bridge), but is there a way to give a minimum depth to the cross-hair that exceeds beyond the character. This would stop the bullet from going back towards the camera even if something is between it and the player's intended target. Something like the below seems ideal but I can't get it to work: Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f) ); Greatly appreciate what you are doing thank you.
Hello @TheKiwiCoder Im having an issue at destroying the bullet once i shoot it for some reason it is not working and in the hierarchy shows me that the bullets i shot are settled at the hit position, tried to follow along the process aagain but failled to, please provide me some guidance, Also when i fire there are two instances of the tracers, best regards, Lonewolf.
Hey man! I have been following your tutorial. But I have to ask about the CrossHairTarget script. I followed the exact steps you say and all of a sudden my CrossHairTarget just aims at my player's shoulder. Basically, It acts as more as person with a camera than an actual target base. Is there anything around it?
@@TheKiwiCoder It didn't help, It was still shooting backwards though. I tried changing the setting the camera setting or the cinemachine settings but it didn't help as well. Edit: Ok! I found the reason CrossHairTarget is colliding against my character but I don't know how to get around it. Even with your updated code. Update Edit: I solved the Problem. It was the skin mesh Renderer that messes me up. So yeah! To all the people who have trouble with the weapon shooting backwards. Either Just adjust the code that has been pinned by TheKiwiCoder and/or Adjust the Skin Mesh Renderer. Cheers!
Sir i am having a great issue..The physics.raycast is not working..when i am putting anything in else, then the else thing is happening but the transform.position = hitinfo.point is not working...Plz hlp me sir..I wasted about 3 hours but couldnt find anything..how do i continue the tutorial now..plz hlp
I have gotten to the end and now the trail and the impact effects have stopped working and the muzzle is constantly firing. isFiring is not constantly on and updates correctly to mouse inputs but the muzzle flash is constantly on. It is spawning in BulletTracer(clone)'s in the Hierarchy but I cannot see them and everything is set up correctly in the inspector. It was all working fine prior to the bulletdrop/speed updates. The bullet trail works fine if I drag the prefab into the scene the same for the hit effects which makes me think it is an issue with the ray cast. I have troubleshot this issue for some time now and can't figure out where I have went wrong as the code looks verbatim to what you have. using System.Collections; using System.Collections.Generic; using UnityEngine; public class RaycastWeapon : MonoBehaviour { class Bullet { public float time; public Vector3 initialPosition; public Vector3 initialVelocity; public TrailRenderer tracer; } public bool isFiring = false; public int fireRate = 25; public float bulletSpeed = 1000.0f; public float bulletDrop = 0.0f; public ParticleSystem[] muzzleFlash; public ParticleSystem hitEffect; public TrailRenderer tracerEffect; public Transform raycastOrigin; public Transform raycastDestination; Ray ray; RaycastHit hitInfo; float accumulatedTime; List bullets = new List(); float maxLifetime = 3.0f; Vector3 GetPosition(Bullet bullet) { Vector3 gravity = Vector3.down * bulletDrop; return (bullet.initialPosition) + (bullet.initialVelocity * bullet.time) + (0.5f * gravity * bullet.time * bullet.time); } Bullet CreateBullet(Vector3 position, Vector3 velocity) { Bullet bullet = new Bullet(); bullet.initialPosition = position; bullet.initialVelocity = velocity; bullet.time = 0.0f; bullet.tracer = Instantiate(tracerEffect, position, Quaternion.identity); bullet.tracer.AddPosition(position); return bullet; } public void StartFiring() { isFiring = true; accumulatedTime = 0.0f; FireBullet(); } public void UpdateFiring(float deltaTime) { accumulatedTime += deltaTime; float fireInterval = 1.0f / fireRate; while(accumulatedTime >= 0.0f) { FireBullet(); accumulatedTime -= fireInterval; } } public void UpdateBullets(float deltaTime) { SimulateBullets(deltaTime); DestroyBullets(); } void SimulateBullets(float deltaTime) { bullets.ForEach(bullet => { Vector3 p0 = GetPosition(bullet); bullet.time += deltaTime; Vector3 p1 = GetPosition(bullet); RaycastSegment(p0, p1, bullet); }); } void DestroyBullets() { bullets.RemoveAll(bullet => bullet.time >= maxLifetime); } void RaycastSegment(Vector3 start, Vector3 end, Bullet bullet) { Vector3 direction = end - start; float distance = direction.magnitude; ray.origin = start; ray.direction = direction;
awesome tutorial! but I have a bit of a problem, when I add the bullet tracer and start playing it, the startpoint of the bullet tracer is too slow to catch up the gun point and after a few moment it catches up. How can I make this faster?
ok there is an issue in the CharacterAiming Script. When adding the if(weapon.isFired) to the lateupdate method to get the fire rate my unity editor crashes when trying to fire. Not sure exactly what is wrong
@@TheKiwiCoder I made sure of that already. Now what it does if I add that if statement it freezes the editor. But if I take it out I have no problems. But it only freezes when I aim and click the left mouse button
Greate tutorial series. Loved it. Has anybody else faced the below issue? hitEffect.transform.position = hitInfo.point; hitEffect.transform.forward = hitInfo.normal; hitEffect.Emit(1); The hitEffect is not facing the surface. As a matter of fact its rotation is unchanged and thus is visible from only one direction and sometimes looks odd. I also tride rotating it to "Quaternion.LookRotation(hitInfo.normal)" n it worsened and was no longer visible in any direction. Could any of you help me here.
Why am i getting this error? i can shoot a couple of times then its stuck on shooting. MissingReferenceException: The object of type 'TrailRenderer' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. RayCastWeapon.RaycastSegment (UnityEngine.Vector3 start, UnityEngine.Vector3 end, RayCastWeapon+Bullet bullet) (at Assets/Scripts/RayCastWeapon.cs:105) RayCastWeapon+c__DisplayClass20_0.b__0 (RayCastWeapon+Bullet bullet) (at Assets/Scripts/RayCastWeapon.cs:80) System.Collections.Generic.List`1[T].ForEach (System.Action`1[T] action) (at :0) RayCastWeapon.SimulateBullets (System.Single deltaTime) (at Assets/Scripts/RayCastWeapon.cs:74)
@@misc-i6q very weird. There are two particle/unlit shaders I think.. one for URP and one for standard. Check your using the right one. If you can see an outline the. The geometry is being created correctly. If not.. try changing the time length or something. Sorry that’s about as much help as I can give
UPDATE:
Hi all, there is a small bug in the CrossHairTarget script which will cause the gun to fire backwards. Convert lines 22/23 to this:
if (Physics.Raycast(ray, out hitInfo)) {
transform.position = hitInfo.point;
} else {
transform.position = ray.origin + ray.direction * 1000.0f;
}
Thank you, silly of me not checking the comments before being stressed out by this bug. Thank you for this great tutorial!
@@rosegarrote9666 in a later video he said that he's going to
I had to rewrite the whole thing, still appeared came to check and saw this comment
all i did was flip the Y position of the raycastOrigin in the inspector and that was simple enough lol
This made me bug even more lol
For those people who have a character close to camera, consider to use layers or tags to ignore the player on raycasts, or every ray cast will be absolute messy. Kiwicoder has a character far from the center of the cam, however, he can face problems when the cam is moving closer to character in some situations like when cam avoid clipping.
PD: great tutorials dude (clap!, clap!, clap!)
You are the legend. Honestly, one of the best tutorial channel. The explanations are so clear. Absolutely deserve a lot of subscribers but for now just one more by me :)
Thank you! ✌️
This video deserves more view, literally hand to hand tutorial.
Thank you 😊
I know this is coming late from me. But I'd you're seeing this comment I just wanna thank you for how your tutorial have changed my Game Dev Journey
Man just wanted to say this series is awesome! Thanks for taking the time to explain all this, it helps SO MUCH!
Another kiwi I've just started really getting into unity it's good to see another kiwi.
For the ones who has a computer freeze after running game, it is happening because of the while loop. Change while( accumulatedTime >= 0) to while( accumulatedTime >= fireInterval). Fixed.
I just finished this video. Your videos on this topic so far have been the best ever on RUclips. Your detailed explanation of the complex content puts some courses on Udemy to shame. If you do a course on Udem, I will be one of the first to buy it. Great content!.
If anyone cannot see the red line (created by Debug.DrawLine), make sure to enable gizmos
Thanks for the tip!
but I still cannot see the red line
@@nikhstudiosthe1 For those still having issues, make sure you are adding Gizmos to the scene you are actually looking at! If you add the Gizmos in the "Game" scene, look there!
Thank you so much for this tutorial !
I had some troubles as the particles of the pack were different for me, with other settings. But I changed my projectile based shooting system to a hitscan one after seeing your tuto and it fix a lot of issues that I had. I'll just need to watch the 2nd part of the video now to implement some velocity and drop :) Thanks again !
You’re very welcome! Good luck!
This tutorial solved my biggest game maker problem. Thanks a lot!
cool beans, thanks
I made a actual pooled projectile spawn system. But i needed something like this and didn't know trail renderer was a thing.
Thank you hahaha.
Best Unity shooter tutorial made EVER! YOU ROCK SIR
Amazing dude keep up the good work btw thnx for the tutorial series. i have only done game dev for 5 month now and i couldnt really understud c# or programing and i just kept researching and i saw your chanell and i kept following until i finished the series and i looked back at the code and i slowly understud how c# and programing works and then i changed it to an fps and im having with trying to make a game of my so thank you kiwi coder keep up the good work.
Excellent tutorial! I'm amazed at how much the muzzle flash and hit effects add to the realism. I checked a bunch of other comments to see if you had answered this question, so hopefully I'm not making you repeat something.
How do you handle raycasting at objects that are really close to the player? I'm using a very similar raycast system from the center of the screen and making my bullets travel from the tip of the gun towards my aim target. If I walk up to an object so that I'm basically touching it, it become very obvious that bullets are shooting almost sideways out of the gun.
You are a Beast man
That's the best way to instantiate a hit effect I can imagine! You are a legend!
Super awesome tutorial once again. took me all day but I got it all working lol. As a request it would be cool to see a state based character controller for like running jumping climbing ladders or walls etc later. or some tutorials on how to equip stuff to your character from like a shop (clothing items/armour etc). Thanks again!
Thanks for the feedback!
These tutorials are just beautiful. Please create a patron so I can support you a bit. :)
Hey Chase! If you'd like to support the channel you can find my Patreon here: www.patreon.com/thekiwicoder Thanks!
I'm having an issue with my raycast Debug.DrawLine at around 9:55. The line is not appearing. I have added Debug.Log(hitInfo.point) to print the endpoint to the console, which works properly, so the ray is being cast and intersecting with objects. Idk why the DrawLine is not working. Anyone have any suggestions?
Edit: Never mind I just didn't have gizmos enabled.
i did the same thing lolol
I ran into the same issue - make sure that both your Scene and Game windows have "Gizmos" turned on :)
Господи. 4 часа потратил на решение. А оказалось что сраная gizmos не была включена..... Спасибо, Бро.
The last part of the video (the part where you mostly do the scripting for bullet drop and bullet simulation) is kinda confusing and you went over it super quickly. It would be helpful to have like a conclusion or an overview of what you were doing (something like a drawing or illustration that explains the logic behind the script). That's just my two cents.
I don't have RaycastWeapon
Edit: got it to work. I just don't know how to delete all the instantiated objects
Edit2: nevermind, I just didn't see the tutorial fully.
Ok now I got everything to work. Thank you for the tutorial :D
You can also Calculate the Screen Width and Hight / 2 and make Target Center
Thank you so much for this tutorial. Especially the final section
Since you seem very knowledgeable
Excellent tutorial! I learned a lot from it. Thank you!
At 3:28, I noticed you put the input processing code in the LateUpdate method instead of Update method. Are there any good reasons to do that, why not just put the code in Update method?
No, input should be processed as early in the frame as possible. I was probably fighting against a cinemachine update ordering issue with animation rigging
Great video. Thank you for your tutorial.
Firstly a huge congrats! It is the best Raycast shoot tutorial I have seen. I am surprised by the so advanced level. How many years are you programming C#?
Thanks man, I graduated in 2008. So a while now 😅
Dude But why U making Everything public instead [SerializeField]
thanks for the last part. I wasted 2 days finding and thinking how to perform that. although I didn't understand most of the codes for making a lot of functions but things are working for me and I can make the work done by that :D
Woop woop 🙌
Thanks you very much for your tutorial on raycast ! For my video game, I don't need the "bullet drop" part, but until that, it's was interesting !
A super tutorial with wanderful explanation.
I love this tutorial but after the 25 min it getting. Confusion for begginer like me and others so please explain everything thank you
U lost me at 26:39, which buttons do i have to press to open that?
Open the trail renderer component, and drag the game object around in the scene view
Ctrl + .
Still fantastic, much appreciated mate!
Hello man!
I did follow your tutorial but i can't manage to get my material right for the bullet tacer. It's invisible for me. I do see the fact that it's there whe i select it in my inspector.
Have you ever had such an issue?
great tutorial btw :)
Thanks :) check which shader it’s using on the material.. also post this in the discord, it’s a bit easier to help there.
Make sure you didn't accidently apply a Line Renderer, like I did :D
The problem with the MuzzleFlash at min 7:12 does not happen for me in Unity 2020.1.10, just FYI. It works without adjusting the particle system.
That’s great, I filed a bug with Unity and it sounded like they found a fixed it. Nice to see bug reports work!
Same here Unity 2020.3.2f1 LTS
same here 2020.3.4f1 and now also in Unity 2020.3.6f1;
Amazing content keep going
Getting a bullet to move over time from a ray is FAAAAARRRRRR more complicated than I thought
It can get more complicated too!
For those who are having white boxes in URP with the hiteffect particle, change the Dust shader to URP/Particles/Simple Lit
Thank you, couldn't figure this out. Appreciate the answer!
Great tutorial love it you did it again !! Will you be doing a weapon switch ??
From rifle to pistol for example and maybe ammo counter maybe
Thanks! Yeah I'd like to cover that. Handling different weapons easily and attaching them at runtime :)
TheKiwiCoder You welcome mean anytime 👌🏿👌🏿💪🏿💪🏿💯💯
Very nice. How about sound effects and shells dropping on the floor?
Man yes, sound effects I really want to add.
Another kiwi? Great tut by the way
Fantastic Video! Extremely well taught, easy to understand, and pleasant to listen to. Thank you so much, this helped a ton! :D
Amazing stuff!!! Golden guy this TheKiwiCoder!!!
This is awesome! Thank you so much. I am trying to make an "energy cannon" style weapon that shoots a decent-sized "energy ball" projectile at a slower speed than a bullet would travel. The methods you used seem like they should work for this use-case! Originally I was going to use a rigidbody with a sphere collider and Unity's physics system to calculate travel & hit detection, but I read that this may be performance heavy and a raycast-based projectile is more optimized. I particularly like the equation-based (deterministic) positioning of the bullet based on time.
Some questions for you:
1. Why did you use 'LateUpdate' to calculate bullet travel rather than 'Update' or 'FixedUpdate'? I trust that this works, but it wasn't explained in the video.
2. Would it be "wrong" to use 'FixedUpdate' for calculating bullet travel/impact? And what are the implications of doing so? (For example, poor performance?)
For #2 I understand that using 'Update' or 'LateUpdate' would always provide smooth visual movement of the bullet (since 'FixedUpdate' time may not always line up with the 'Update' loop, causing jitter). However, I'm second guessing myself because isn't 'FixedUpdate' the right thing to use if we're doing a physics calculation such as a bullet hitting a wall? If we used 'LateUpdate' then wouldn't the accuracy of bullet impact calculations differ based on each player's framerate, putting lower-spec players at a disadvantage? Could a combination of both be used - 'FixedUpdate' for hit detection and 'LateUpdate' for the visual? Or does it actually not matter that much and I am overthinking it?
For a competitive multiplayer game I just want to make sure things are accurate *enough*, even if 'LateUpdate' is used.
It’s been a while since I made this but I think I used late update to ensure animation rigging had run and the muzzle position was up to date when spawning the bullet.
But you’re right though fixed update sounds better for simulation and use late update for the visuals.
For a multiplayer game though you might be running the hit detection on the server which is untied to the clients frame rate.
Thanks for the great tutorial. I am learning so much with your videos. You are really awesome.
I noticed an issue with the fire rate and have not found a solution to that yet. If i click as fast as i can, i am able to ignore the fire rate of the gun. This is easier to spot when the fire rate is set to a low value (e.g. 5). It has to do with resetting accumulatedTime and FireBullet() in StartFiring(). Since i removed both those line from StartFiring() function i am not able to fire faster than the fire rate, but also some manual shots get ignored because the accumulated time is never reset.
You're welcome!
Thanks for spotting that. To fix it: accumulatedTime should be updated even when not firing, so move it into UpdateBullets for example. Then inside StartFiring, check that it is greater than zero before resetting (if it is negative, it's still in the cooldown period).
@@TheKiwiCoder Your suggestion works like a charm. Thanks!
@ @TheKiwiCoder how exactly would this look like ? if(accumtime > 0.0f){ accumtime = 0.0f;} and in updateBullet ?
@ Maybe u can post this part of code? I got the problem that it looks like i fire 2 Bullets in a row and i mean it have something to do with the accumulated time and firerate.... would be very nice men ^^ ( also happend on pistol with fireRate of 1 -> always shot 2 bullets.)
@@TheKiwiCoder I don't get this solution. Could you be a bit more specific please?
Brilliant video - again! How do I change the rotation of the gun at this point? It's not quite pointing at the target dot when I aim. I can't find a way of doing it now everything is hooked up. Thanks
Hey, the multi aim constraint should be pointing the gun at the dot. Bring the AimLookAt game object in/out from the camera to change the angle.
@@TheKiwiCoder Thanks for that but it doesn't seem to do much. I'd like to change the position of the gun in the hands but now the aiming system is working I can't do it when in play mode as I can't aim and adjust settings at the same time. I can't temporarily turn off things either so I can reposition my gun and hands. When in play mode I can't see my gun as it's behind the player - I'd like to move it if possible. Any thoughts would be welcome -thanks again - brilliant tutorials
Ah ok, what you can do is rather than aiming the weapon, create a weapon holder object, and add the weapon as a child of that. Attach a rig constraint to it which you can then position. It’s explained a bit more in this video: ruclips.net/video/bIOxl8iDWoU/видео.html
@@TheKiwiCoder Awesome - thank you so much - I'll have a look. Can't wait for more of your tutorials - you are the best on RUclips.
This is a great video. I found that I had to test that bullet.tracer wasn't null in RaycastSegment. Weirdly the video stutters for me. 1080p60. No other makers videos do. Strange. Doesn't take away from the video though. Thanks ☺
For now im just copying for my uni project but i will be back to learnd this from the start
maybe there is a problem if crosshair goes to sky and bullet shoot them bullet goes to player position how can we fix this ?
having the same issue
Maybe use layers to ignore the player / whatever is in the way, also i was using projectile prefabs instead of raycast, that way you need to normalize the direction vector, otherwise it gets faster the further the crosshair target is from the gun
Absolutely love this solution, and the steps were really well explained!
I do have one question, about the ray section function. You make a raycast from the start point, in the direction of and distance to the end point. Are there any advantages to this, compared to a linecast from start to end?
i couldnt make the material of the trail cuz i didnt find the same values to change can u upload the material ? i mean the material of the bullet tracer thanks for the tutorial it was helpful
Very nice!
Heya, the gun always seems to fire twice when I click. Any idea why that might be happening?
Never mind, fixed it! The FireBullet() call in StartFiring was happening at the exact same time as when UpdateFiring would call it as well. Just removed the reference in StartFiring and now I'm shooting one bullet when I first click. It's been a few weeks since I last watched this video so maybe I missed a bit where you addressed this.
Hey @TheKiwiCoder!
I was just wondering, do your bullets also persist (dont get destroyed) when you aim and fire at horizon? I notice in the code that the maxLifetime of the bullet is only set OnHit, but not in the else statement.
Awesome tutorial vids my man!
Keep it up!
@TheKiwiCoder Hey man, having a small issue. If I move my character little by little the animation pose becomes warped until my normal holding the gun pose looks like broken wrists and physics from a world Doctor Strange frequents. It starts off behaving perfectly, but maybe bleeding kinematics causing pose warping? (The subtle inaccuracies adding up over hundreds of tiny movements until the referenced transforms resemble nothing of the initial values)
I'm not sure but I'm at a loss. Did you or anyone else here experience anything like this?
Amazing job man! This playlist is gold 👍🏼
How would you implement an aim zoom that zooms in on the crosshair? I tried changing the field of view, but it just focuses on my look at target.
I would change a combination of FOV and zoffset. Another thing to experiment with is creating a separate dedicated camera and blend between them using cinemachine
He made a new video that goes over this topic exactly, if you still haven't figured it out.
hi agin i find why bullet tracer dose not destroy because i froget enable autodestruct tick in trail renderer component 😅
Loving it already? Next up? Weapon switching? And also if you don't have weapons then walk normally... How that gonna happen?
I'm hoping to do a pickups video at some stage that will allow weapons to be attached at runtime.
@@TheKiwiCoder awesome!
There is a problem I'm having that if I point the gun towards the sky, there are no tracers. the reason for that is because hit.point is null so when the raycast doesn't hit anything then the trail is not seen. please help
@TheKiwiCoder Even I am facing the same issue. Please help.
Add massive collider in the sky. Simple.
@@USBEN. ok thanks
@@USBEN. there however is a problem the it looks like the bullet suddenly stops moving mid air. so you need to put the collider up reaaaallllly high
@@FelineRaptor-gv4te Make it trigger, the raycast will have something to hit and the collider wont collide with any object that way.
how would i make it to where the tracer shows up even when i shoot in the air
Hey when i go fullscreen my particles just disappear i dont know what to do here someone have a fix?
it says rig could not be found when I make it a pub variable and its not used in the script?
Who ever dropped that one dislike......... IM COMING FOR U
Now there are two of them..this is getting out of hand
I saw these videos back in the day now i was working on a Shooting game ran into the same issue about crosshair.
I was thinking about the solution. Then i remembered there was a Legend "TheKiwiCoder" who posted the solution about same issue
To anyone who has the muzzle flash going non-stop, turn off the "play on awake" option
what the name of background music? that is very well
I installed the "universal render pipeline", to be able to use it in the shader, but the material was transparent, is there any alternative?
Did you upgrade project materials?
@@TheKiwiCoder Yes, I did it, and besides the transparency, some became pink! hahaha but no problem, I used something else
How would you make an object pool out of the bullets? This instantiates and destroys objects constantly which isn't optimal. I am having some issues with trying to modify your script to be able to use object pooling
This might help: docs.unity3d.com/2021.1/Documentation/ScriptReference/Pool.ObjectPool_1.html
Replace new Bullet with pool.Get(), and call pool.Release() on the bullet before removing it from the list.
Sir....
I upgraded along this video. but i met big problem. All world changed pink color. material destroy error.
What can i solve this problem? please sir........
Hey, upgrading materials should fix the pink materials. Check the shader on the material is set to ‘Urp/lit’ shader. There are other videos on RUclips about this topic that should help. Good luck!
Check This:
ruclips.net/video/VJxrdrgbuTE/видео.html
carrot if you’re using synty studios asset pack you might want to check their RUclips tutorial on how to obtain their latest URP compatible materials. Sci fi city pack which is used in this video series has been upgraded.
I know this is old, but I just ran into this problem. In case anyone else does too, I am posting the solution I found.
First follow this docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.3/manual/InstallURPIntoAProject.html
Then this docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.3/manual/upgrading-your-shaders.html
My terrain was still pink so I just made a new one. Idk if there is a better way.
@@TheKiwiCoderSetting the material to urp/lit instead of urp/particles/lit worked for me, thanks!
greeat tutorial, i have only one small problem, the firerate is too fast no matter which value i put in the Fire Rate.
Best, massive lifesaver
Amazing ❤️
I really like your teaching style I get why you writing the code you are, not just following along.
But I have found a bug and haven't found the solution in the comment section:
Basically whenever the player fires with the crosshair on something behind the character (perhaps the character is running under a bridge) it shoots backward towards where the crosshair is placed.
I know it is down to the ray destination being where ever the cross-hair is (in the above example that location would momentarily be the bridge), but is there a way to give a minimum depth to the cross-hair that exceeds beyond the character. This would stop the bullet from going back towards the camera even if something is between it and the player's intended target.
Something like the below seems ideal but I can't get it to work:
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f) );
Greatly appreciate what you are doing thank you.
@TheKiwiCoder Also looking at your patron, are you active on the discord chat community also?
@@trentwilliams7829 hey can u give me the raycastweapon script pls just copy paste the code heere my code is not working idk why
hi thanks for this tutorial but i have a problem my bullet dose not destroy after maxLifeTime can you help me ? 🙂
Thank you much , Your video is best experience to me.
Hello @TheKiwiCoder Im having an issue at destroying the bullet once i shoot it for some reason it is not working and in the hierarchy shows me that the bullets i shot are settled at the hit position, tried to follow along the process aagain but failled to, please provide me some guidance, Also when i fire there are two instances of the tracers, best regards, Lonewolf.
send your code
Hey man! I have been following your tutorial. But I have to ask about the CrossHairTarget script. I followed the exact steps you say and all of a sudden my CrossHairTarget just aims at my player's shoulder. Basically, It acts as more as person with a camera than an actual target base. Is there anything around it?
I pinned a comment with a small fix to that script, check if that helps.
@@TheKiwiCoder It didn't help, It was still shooting backwards though. I tried changing the setting the camera setting or the cinemachine settings but it didn't help as well.
Edit: Ok! I found the reason CrossHairTarget is colliding against my character but I don't know how to get around it. Even with your updated code.
Update Edit: I solved the Problem. It was the skin mesh Renderer that messes me up. So yeah! To all the people who have trouble with the weapon shooting backwards. Either Just adjust the code that has been pinned by TheKiwiCoder and/or Adjust the Skin Mesh Renderer. Cheers!
IN MY CASE WHEREEVER I CLICKED ON SCREEN LINE IS ONLY DRAWING DOWNWARD SIDE ,,,IS THERE ANY SOLUTION?
Sir i am having a great issue..The physics.raycast is not working..when i am putting anything in else, then the else thing is happening but the transform.position = hitinfo.point is not working...Plz hlp me sir..I wasted about 3 hours but couldnt find anything..how do i continue the tutorial now..plz hlp
Try adding Debug.DrawSphere in the code to see where the ray cast is getting hit.
Amazing video !!! =)) Thanks
I would like to know if it is possible in any way to apply a particle system to the bullet as well?
Hey i have a problem, my material for my bullet rail is transparent and idk why
Maybe check the shader on the material is compatible with your render pipeline
You need to set the URP first after adding it
@@TheKiwiCoder i will check thank you
@@itgun I also have the same problem
amazing thanks for video 😍😍😍
I have gotten to the end and now the trail and the impact effects have stopped working and the muzzle is constantly firing. isFiring is not constantly on and updates correctly to mouse inputs but the muzzle flash is constantly on.
It is spawning in BulletTracer(clone)'s in the Hierarchy but I cannot see them and everything is set up correctly in the inspector.
It was all working fine prior to the bulletdrop/speed updates.
The bullet trail works fine if I drag the prefab into the scene the same for the hit effects which makes me think it is an issue with the ray cast. I have troubleshot this issue for some time now and can't figure out where I have went wrong as the code looks verbatim to what you have.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaycastWeapon : MonoBehaviour
{
class Bullet
{
public float time;
public Vector3 initialPosition;
public Vector3 initialVelocity;
public TrailRenderer tracer;
}
public bool isFiring = false;
public int fireRate = 25;
public float bulletSpeed = 1000.0f;
public float bulletDrop = 0.0f;
public ParticleSystem[] muzzleFlash;
public ParticleSystem hitEffect;
public TrailRenderer tracerEffect;
public Transform raycastOrigin;
public Transform raycastDestination;
Ray ray;
RaycastHit hitInfo;
float accumulatedTime;
List bullets = new List();
float maxLifetime = 3.0f;
Vector3 GetPosition(Bullet bullet)
{
Vector3 gravity = Vector3.down * bulletDrop;
return (bullet.initialPosition) + (bullet.initialVelocity * bullet.time) + (0.5f * gravity * bullet.time * bullet.time);
}
Bullet CreateBullet(Vector3 position, Vector3 velocity)
{
Bullet bullet = new Bullet();
bullet.initialPosition = position;
bullet.initialVelocity = velocity;
bullet.time = 0.0f;
bullet.tracer = Instantiate(tracerEffect, position, Quaternion.identity);
bullet.tracer.AddPosition(position);
return bullet;
}
public void StartFiring()
{
isFiring = true;
accumulatedTime = 0.0f;
FireBullet();
}
public void UpdateFiring(float deltaTime)
{
accumulatedTime += deltaTime;
float fireInterval = 1.0f / fireRate;
while(accumulatedTime >= 0.0f)
{
FireBullet();
accumulatedTime -= fireInterval;
}
}
public void UpdateBullets(float deltaTime)
{
SimulateBullets(deltaTime);
DestroyBullets();
}
void SimulateBullets(float deltaTime)
{
bullets.ForEach(bullet =>
{
Vector3 p0 = GetPosition(bullet);
bullet.time += deltaTime;
Vector3 p1 = GetPosition(bullet);
RaycastSegment(p0, p1, bullet);
});
}
void DestroyBullets()
{
bullets.RemoveAll(bullet => bullet.time >= maxLifetime);
}
void RaycastSegment(Vector3 start, Vector3 end, Bullet bullet)
{
Vector3 direction = end - start;
float distance = direction.magnitude;
ray.origin = start;
ray.direction = direction;
if (Physics.Raycast(ray, out hitInfo, distance))
{
hitEffect.transform.position = hitInfo.point;
hitEffect.transform.forward = hitInfo.normal;
hitEffect.Emit(1);
bullet.tracer.transform.position = hitInfo.point;
bullet.time = maxLifetime;
}
else
{
bullet.tracer.transform.position = end;
}
}
private void FireBullet()
{
foreach(var particle in muzzleFlash)
{
particle.Emit(1);
}
Vector3 velocity = (raycastDestination.position - raycastOrigin.position).normalized * bulletSpeed;
var bullet = CreateBullet(raycastOrigin.position, velocity);
bullets.Add(bullet);
}
public void StopFiring()
{
isFiring = false;
}
}
awesome tutorial! but I have a bit of a problem, when I add the bullet tracer and start playing it, the startpoint of the bullet tracer is too slow to catch up the gun point and after a few moment it catches up. How can I make this faster?
I haven’t tried this myself, but you could try running the bullet code inside late update. Interested to know if this works!
ok there is an issue in the CharacterAiming Script. When adding the if(weapon.isFired) to the lateupdate method to get the fire rate my unity editor crashes when trying to fire. Not sure exactly what is wrong
Oh man if the editor is crashing something is bad. Which version are you using? Try deleting your library folder
@@TheKiwiCoder I am using 2019.3.0f6
Big Shot Studios also check the weapon is not null, I think I skipped that bit
@@TheKiwiCoder I made sure of that already. Now what it does if I add that if statement it freezes the editor. But if I take it out I have no problems. But it only freezes when I aim and click the left mouse button
Big Shot Studios have you tried attaching a debugger? There could be an infinite loop somewhere
If have the issue, since I made the code changes at the end of the video I see no tracer anymore.
I was able to fix it by changing in the CreateBullet from bullet.tracer.AddPosition(position) to bullet.tracer.AddPosition(raycastOrigin.position);
Greate tutorial series. Loved it.
Has anybody else faced the below issue?
hitEffect.transform.position = hitInfo.point;
hitEffect.transform.forward = hitInfo.normal;
hitEffect.Emit(1);
The hitEffect is not facing the surface. As a matter of fact its rotation is unchanged and thus is visible from only one direction and sometimes looks odd.
I also tride rotating it to "Quaternion.LookRotation(hitInfo.normal)" n it worsened and was no longer visible in any direction. Could any of you help me here.
Finally fixed it. I had kept scale 0 and position was not 0. After fixing it started working.
God...Thank you man
I just noticed that for me the particle (when I increase their size to shoot "spheres") appears flat instead of spherical, any idea how to fix this ?
38:28
To uncomment more than one line. You can select all the commented text and press. ctrl +K, U
Thanks for the tip!
Is this using the "New" Input system?
God no
@@TheKiwiCoder just wanted to check, I figured it wasn’t lol
Why am i getting this error? i can shoot a couple of times then its stuck on shooting.
MissingReferenceException: The object of type 'TrailRenderer' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
RayCastWeapon.RaycastSegment (UnityEngine.Vector3 start, UnityEngine.Vector3 end, RayCastWeapon+Bullet bullet) (at Assets/Scripts/RayCastWeapon.cs:105)
RayCastWeapon+c__DisplayClass20_0.b__0 (RayCastWeapon+Bullet bullet) (at Assets/Scripts/RayCastWeapon.cs:80)
System.Collections.Generic.List`1[T].ForEach (System.Action`1[T] action) (at :0)
RayCastWeapon.SimulateBullets (System.Single deltaTime) (at Assets/Scripts/RayCastWeapon.cs:74)
The trailrenderer has an auto destruct property which destroys the game object when it stops emitting. Checking for null should fix it :)
@@TheKiwiCoder Where would i check for null?
I added a if null, but when i hold it for a while it still pops up
@@TheKiwiCoder So i thought i fixed it , but the bullet hit effect, stays and plays, can you explain the solve for this a bit more?
AlexRak2Dev turn looping off on the particle effect (and child particles)
I need to install wich package for having the Universal render pipeline particle ?
If the textures on the effects show up (the MuzzleFlash01, for example, will be orange/red) you can skip that step.
Hey man !!! You are super
Is the render pipeline absolutely necessary because I couldnt see the bullet tracer or raycast line
It’s not needed no. Double check your material is using the correct shader for your pipeline
I'm slightly confused, I was using the same one as you, in particles then unlit
@@misc-i6q very weird. There are two particle/unlit shaders I think.. one for URP and one for standard. Check your using the right one. If you can see an outline the. The geometry is being created correctly. If not.. try changing the time length or something. Sorry that’s about as much help as I can give
Wait I wasn't using urp but I was using a urp shader, should I use standard then, the only problem is I can't find standard unlit
OK I can see bullets now, but they are red XD, I have no idea how this happened
so how did you get from the previous movement script back to the strafing again, man , you want us to fail