📦 Check out the Grow your skills Mega Bundle here: assetstore.unity.com/mega-bundles/grow-your-skills?aid=1101l96nj&pubref=shootproj 🌐 Learn more about Unity Learn Premium here: unity.com/products/learn-premium?aid=1101l96nj&pubref=shootproj ❤️ Using this Affiliate Link helps support the channel
I making a fnaf fan game on unity and i can’t make a Good ai I did wander but well it traces the player it goes back to wandering and it’s been doing my head in can you help I only know C# and I’m learning python
Bro how can I get your library just like "using code monkey.utils;" I can't watch your tutorial because of that. Plz help me bro, I am a big fan of Brackeys,blackthornprod and Dani. I wish you to be one of my idol bro plz help me with some kind of link thank you bro
There's another way to detect projectile collisions, which is ideal for if you want the projectile to travel very fast, but not be an instant-hit like how a raycast would accomplish. Using the distance check or physics system can both occasionally allow projectiles to pass through targets if the projectile is traveling fast enough (even if you're using a rigidbody with continuous collision detection), causing something like this to happen... [Projectile last frame] [Target] [Projectile current frame] >===> (O) >===> ...Where the position of the projectile between the last and current frame is at a great enough distance to completely pass the target, never intersecting with it. The trick to solve this is by having the projectile perform a raycast backwards to the position it was in on the previous frame, and detect if the raycast has intersected with anything, which would look like this: [Projectile last frame] [Target] [Projectile current frame] [x = raycast hit] >===>------------------------(O)x------------------------>===> So far, I've had a 100% success rate with very fast projectiles hitting targets using this method.
I've been searching for a RUclips video that showed this method with no luck (I think I saw it a year or two ago and only vaguely remembered it) so thank you so much for this comment
@@bishopjackson2264 Been awhile since I worked with Unity, but it might look something like this: public class Projectile : MonoBehaviour { [SerializeField] private RigidBody _projectileBody; [SerializeField] private LayerMask _hitMask; private Vector3 _lastFramePosition; // Whenever this behaviour is first instantiated/re-enabled in the scene, ensure _lastFramePosition is up-to-date and initialize its body velocity. void OnEnable() { UpdateLastFramePosition(); _projectileBody.velocity = transform.forward * 100 } // Ensure _lastFramePosition is continuously updated every frame. void Update() => UpdateLastFramePosition(); // Detect raycast hits every FixedUpdate step. void FixedUpdate() => DetectRaycastHit(); void UpdateLastFramePosition() => _lastFramePostion = transform.position; void DetectRaycastHit() { // Cast a ray from our current position to our previous position last frame. if(Physics.LineCast(transform.position, _lastFramePosition, out RayCastHit hit, _hitMask)) { // The raycast hit something - process the hit logic here. } } }
One of the variations on the first bullet would be to have a raycast from the last position to a new position to act as continuous collision substitution. That will allow fast non Rigidbody objects to test collision without checking all targets.
Hey, I've just made something similar for my own project and I have a few suggestions to your code. To instantiate the bullet you can write something like this: Instantiate(Bullet, aim.position, aim.rotation); And then in the Bullet class you only need to write: void Start() { Destroy(gameObject, 5f); } // Update is called once per frame void Update() { transform.position += transform.forward * Time.deltaTime * 100; }
Literally started to look for a video like this a week ago. You good sir have earned yourself a new subscriber. Please continue doing quick yet indepth videos like this one on small mechanics. Your approach was perfect.
I need the projectile to have new mechanics and components after upgrading. But adding components when creating the projectile is costly for mobile devices, in my opinion.
Top quality video! Finally I 've fully understood what is a raycasthit! and like the video on the different types of collision, also this video explained in the simplest and clearest way possible the differences between all these methods...I'm very grateful to you!
There are some things you have to change like for the CharacterAim_Base I replaced it with my script that is for aiming which Is PlayerAimWeapon from his other videos
Same, I'm getting a bit lost trying to find all the references between scripts. And I still don't understand why he's getting the Bullet component from the transformBullet...I mean, I'm trying to make it work but without the exact same structure, it's really hard to follow what's happening. Even using the project files, I don't really understand what's happening and when I try to apply it to my own project, I can pass the shootdirection vector to the bullet script, but they default back to 0 once I use them in the update method. I think I'm gonna have to follow another tutorial for this one. It just sucks that it's the only one I can find that doesn't use rigidbodies and I really don't need physics for my project so I was hoping to implement that first technic.
for the readability sometimes using an if statement is better than using the '?', never knows who is gonna read the code, a lot of junior devs don't know what ? means or don't use it
you must have tried to literally copy the whole script word for word instead of doing that just copy the lines where the bullets are instantiated _inside_ a if statement, which checks wether a button is pressed or not edit: nvm that wont work either because of how he intregrates those lines with his premade scripts
Great video, and I just realized that battlefield4 uses the ray cast hit detection method in 3d, I realized it when i shot a rocket in the game and no rocket spawned but there was still an explosion, funny that I was confused and thought the game was bugged, but now I can try and make it myself
great video! just when I was thinking how to merge two lasers and form a third laser to emit the other way without having a hole in the middle. this video enlightened me ~ thank you. oh and what about using particle system for projectiles? Is it good or bad? cuz that seems to be the easiest...would I face problems using that in the long term?
The bullet trace continues past the target after it hits, would you need to modify the bullet trace class to make sure it stops when it hits the target?
You could do a Raycast from the ShootPoint towards the MousePosition and see what objects it hits, then use that for the Trace end point rather than the mouse position
Sure that's another approach. Personally I've never used it simply because transforms or rigidbodies already work great and I'm not very good at creating good looking VFX.
In the PlayerShoot class is it possible to pass the position of the target (from the BulletRaycast class if it hits something) so the weapon tracer doesn't go over the target if it hits it. Thanks for the awesome videos!
Yup that's what I did in my Third Person Shooter bullet, the bullet receives a target position and just moves towards it and destroys when it reaches ruclips.net/video/FbM4CkqtOuA/видео.html
Good video! I downloaded the project and my Unity ver: 2021.3.11f complained about 'using UnityEngine.Experimental.Rendering.light2D' . Most of the project works, but I am curious how to fix that. Thanks!
I see a problem with the transform and the physics solution: When the bullet is fast and the target small the chance is very high that the bullet skips the target since position in Frame x is befor the target and in frame x+1 already behind it. I solved that by checking every frame some space ahead with Physics.OverlapSphere() if the bullet is close enough to a target.
@@CodeMonkeyUnity for anyone else that implements this sometime the continuous solution does not work other. I have very fast bullets and it can actually skip targets. So to fix this I do a raycast between previous position and curren position to see if anything is hit.
I want to do the method of the prefab bullet but I already have a script to use the "object pooler" I would not know how to put this same script to mine because you use your utilities,any help?
Not sure what you mean, an object pooler should be able to handle any prefab, doesn't matter what scripts are attached to it. What specific utility function are you referring to? There's nothing uniquely special about my utilities, you can easily write your own.
Hello sr. Im emiting an object that has vfx but it start small and increase by time to the wanted original size. How to emit it without the increase just original size?
I have two problems, one problem is with the first method, my bullets speed are variable depending how close my mouse is to the player, the second is with the second method, because using add force make the bullets knockback enemies that also have a collider and a rigidbody.
Sounds like you need to normalize the movement vector, it shouldn't care about the distance to the mouse. You can make the bullet a trigger if you want it to not impact enemies
@@CodeMonkeyUnity I am having the same first problem as Sanmiittai is having. My bullet is moving from shootEndPoint to mousePosition, not only that the speed is variable, the bullet also visually disappears at mouse position. I have the shootDir normalized, I can't seem to find what my issue is.
I found a solution to my problem, this solved my bullet speed and disappearing issue. So for the fun of it, I decided to take a look at where on earth is my bullet flying off to and found that it was flying out of the camera view in Z. I also did a Debug.Log of the shootDir which confirmed that indeed my bullet was ALSO moving in Z. I simply zeroed the Z poisiton of mousePosition in the PlayerAimWeapon script by doing mousePosition.z = 0. Hope this helps, it certainly helped me.
I'm having a hard time with the first one. It works up to when I need to pass the shootDirection to the bullet script. The vector looks correct in the Setup function but the default back to 0 in the update function.
Maybe you're never assigning the class field? If the parameter has the same name as the class field you need to do this.shootDirection = shootDirection to make sure you set it
@@CodeMonkeyUnity I found the issue! I completely forgot to pass along the instantiated bullet to the Setup function. So, if I understand correctly (and I might not xD), I was accessing the values of the original prefab bullet at (0,0,0) rather than the values of the instantiated bullet. edit = or rather, I was basically using the Transform values of the PlayerShoot script...I think.
Sure that's another approach. Personally I've never used it simply because transforms or rigidbodies already work great and I'm not very good at creating good looking VFX.
I know this has hit detection with the assumption on shooting projectiles, but what kind of hit detection would be best for button smashers that are just melee combat based?
@code monkey, is there a way to combine the raycast methord with guninputpos, like the slower bullet to prevent fps reg issues? im still new to coding, but so far ive done a few scripts :D
Bro, I am making a 2d top down space shooter. There is a problem in shooting system, that is , when enemy is shooting and I shoot, then the player's bullet is colliding with enemy bullet and the player's bullet is destroyed but the enemies bullet is not destroyed. Can you tell me what to do to make the both bullets passing away without any collision.
If you want your player and enemy projectiles to not collide with eachother you can put them on different layers like “player projectile” and “enemy projectile” then use the collision matrix to turn off the collision of those 2 layers.
I get this weird thing with my GunEndPointPosition that makes it so when i shoot, the bulled starts at like -40x instead of x being 0. I have no clue of what im doing wrong. Help would be greatly appreciated.
Hi i have a question which is the best performant approach for a tower defense type of game that doesnt consume much processing with lots of bullets instantiated?
@@CodeMonkeyUnity So many thanks sensei I'm still learning with dots :) I used your dots path finding system mix with game objects its pretty well but it would be much better if I will be able to do it in full ECS someday :)
I have an issue when using the first method where if I have my cursor on top of my player everything gets messed up, because it shoots from the gun endpoint at my mouse which is on my player, so essentially I shoot backwards. Is there a solution to this?
I work on a 2d platformer, only sideview. Are your options viable in this kind of scenario? I already have some code, but I have troubles with the bullets. They fly up instead away from the player, and I cant rotate them. But could your script work in my case?
@@CodeMonkeyUnity But may I ask one more thing? Could you imagine, why my bullets fly up? I just want to understand why. I posted my code here;forum.unity.com/threads/bullets-fly-up.952832/ I am looking for a solution since yesterday, and I cant wrap my head around the fact, that the bullets fly up, or stay dead in track with vector3.forward
Hi there -- I'm totally stumped on a null reference I'm getting for the event. I started with the 2d character controller tutorial w/ dodge roll & dash, then the aim at mouse tutorial, and now trying to add the shooting. Aiming works fine as I can see from the debug.log of the angle I'm aiming at correctly. The "object reference not set to an instance of an object" error triggers within HandleShooting() on this line: OnShoot?.Invoke(this, new OnShootEventArgs Visual studio is not flagging any issues. Within Unity I have an empty object for the Player (shell) with the logic attached (char controller, player aim weapon, and player shoot projectile scripts) then a child object capsule placeholder, and the only serialized field is for the projectile prefab's transform, which was dragged in. The projectile is an empty game object (shell) w the projectile script attached, and a child visual which is simply a square sprite scaled into a rectangle (aka my placeholder laser visual). Then I have the Aim empty gameobject as a child of the Player (shell) with a child game object for the sprite and another child empty gameobject for the GunEndPointPosition. Save my sanity for +2,000 XP and eternal gratitude. using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerAimWeapon : MonoBehaviour { public event EventHandler OnShoot; public class OnShootEventArgs : EventArgs { public Vector3 gunEndPointPosition; public Vector3 shootPosition; } private Transform aimTransform; private Transform aimGunEndPointTransform; private Animator aimAnimator; private void Awake() { aimTransform = transform.Find("Aim"); aimAnimator = aimTransform.GetComponent(); aimGunEndPointTransform = transform.Find("GunEndPointPosition"); } private void Update() { HandleAiming(); HandleShooting(); } private void HandleAiming() { Vector3 mousePosition = GetMouseWorldPosition(); Vector3 aimDirection = (mousePosition - transform.position).normalized; float angle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg; aimTransform.eulerAngles = new Vector3(0, 0, angle); Debug.Log(angle); } private void HandleShooting() { if (Input.GetMouseButtonDown(0)) { Vector3 mousePosition = GetMouseWorldPosition(); //aimAnimator.SetTrigger("Shoot"); OnShoot?.Invoke(this, new OnShootEventArgs { gunEndPointPosition = aimGunEndPointTransform.position, shootPosition = mousePosition, }); } } using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerShootProjectile : MonoBehaviour { [SerializeField] private Transform projectilePrefab; private void Awake() { GetComponent().OnShoot += PlayerShootProjectile_OnShoot; } private void PlayerShootProjectile_OnShoot(object sender, PlayerAimWeapon.OnShootEventArgs e) { Transform projectileTransform = Instantiate(projectilePrefab, e.gunEndPointPosition, Quaternion.identity); Vector3 shootDir = (e.shootPosition - e.gunEndPointPosition).normalized; projectileTransform.GetComponent().Setup(shootDir); } } I don't think this last script is involved in the error, but just in case.. this is the "Bullet" script from the video using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { private Vector3 shootDir; public void Setup(Vector3 shootDir) { this.shootDir = shootDir; } private void Update() { float moveSpeed = 100f; transform.position += moveSpeed * Time.deltaTime * shootDir; } }
Thank you for the answer! I didnt know about the normalized part. I solved this just yesterday by doing ScreenToWorldPoint on the Input.mousePosition. How expensive is it to cast such a Ray on every frame? I need to check if the player would hit the enemy and if yes, then shoot him automaticly. Is raycasting a good solution or is it too expensive?
I'm having a problem i can't understand When i shoot, the bullet goes in the direction of the mouse compared to the center of the scene instead of the player position Any ideia of how to solve this??? My code looks like is exactly to the one in the video
@@CodeMonkeyUnity So, it seems everything is exactly how it should be Player Position and Mouse Position is following my movement right The same goes with my AimDirection and ShootDir And the Angle is rotating around me I still don't get whats happening :\
I know that is old video but I have really weird problem my bullets don't fly flat my I do a top down game (2D) and my shooting position have served 0 in rotation but bullet still don't fly flat Any solution for this, some ideas
Hmm... does the collision system in Unity account for frame rate differences? I made a game in Java before and had to write my own code to account for that stuff. Would be nice to not have to do that.
Yes, in your rigidbody you can change the collision detection between Discrete where the object teleports to the next position and then checks for collisions Or set it to Continuous and it will detect collisions between the start and end positions
This is showing how to shoot projectiles from scratch. For the character I covered it here ruclips.net/video/Bf_5qIt9Gr8/видео.html The weapon aiming here ruclips.net/video/fuGQFdhSPg4/видео.html
Bullet are too fast for collision and it is saying destroying object may cause loss data plz fix my problems Edit = thank For reply but this are baby solutions and by the way I have already fix it my bullet speed. Was 3000 and it was going through wall so I want to destroy it on collision with other objects. So first I use trigger enter but unfortunately trigger enter unable to catch frame due to bullet high-speed So i used raycast for collision detection of bullet
I am having such an issue with this. I have used the code exactly as it is and the bullets do not move, they just hover in the spawn location. Has anyone else had this issue?
Are you moving them with a rigidbody? Did you set the velocity? Make sure you're not spawning them inside a collider Add some Debug.Log to make sure the code is running
@@CodeMonkeyUnity thanks for those tips, I will try them after work sometime this week. Got to a stage where even at work all I think about is my indie game dev projects and your videos alongside Thomas Brushes have helped a tonne.
How can I contact you because you can work with me in the future Because you are one of the geniuses that I want to join my team in the future all the best from anass i hope to reply me soon
@@juicedup14 Oh that one depends on how you handle the weapon aiming. If you're rotating a game object you can use a invisible transform to position it ruclips.net/video/fuGQFdhSPg4/видео.html In my case I also have an invisible point baked into my animations.
I HAVE A HUGEEEEE ISSUE with firing the Gun, the bullet spawn lags behind just a small distance behind, no matter what direction I move in, depending on speed and height, like if I am running or Jumping, or just side strafing, the bullet spawnpoint shifts side to side, it sucks, please help. If you could point me in the right direction or offer your advice, I would be forever in your debt. So, Basically the bullets are spawning from where I was a second or so before, rather than from where I am. It makes the bullet spawnpoint to shift side to side, Help....Please. Here is the code I am using using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gun : MonoBehaviour { public float speed = 80; public GameObject bullet; public Transform barrel; public AudioSource audioSource; public AudioClip audioClip; public void Fire() { Instantiate(bullet, barrel.position, barrel.rotation).GetComponent().AddForce(barrel.forward * speed); audioSource.PlayOneShot(audioClip); Destroy(bullet, 2); } }
I making a fnaf fan game on unity and i can’t make a Good ai I did wander but well it traces the player it goes back to wandering and it’s been doing my head in can you help I only know C# and I’m learning python
@@CodeMonkeyUnity i made it wander but i need it to chase the player not to damage the player if it hits the player the player gets jump scared and sent to the title screen but my problem is i cant get the AI to wander and do chase in the same script
OnCollisionEnter is triggered when the Physics System updates so if you leave the FixedUpdate at the default of 50 times per second then at the most it will take 20ms If it is indeed delayed by 1 second then the issue is not with OnCollisionEnter
@@CodeMonkeyUnity well, the intro was long and basically duplicate. You have went through the same routine twice. Explaining why you are making the video sponsered content into explaining why you make the video into sponsered content. I know what the video is about, I clicked the thumbnail. If the actual content is not withinthe first minute I lose intrest. I am happy that you asked and did not just ignore my rather crude response
Transform bulletTransform = Instantiate(Bullet, ToFirePoint , Quaternion.identity show to me Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Transform'
You defined Bullet as a GameObject which means the Instantiate(); function will return a GameObject and not a Transform either change Bullet to Transform or call Instantiate().transform
Really usefull video but i have issue and i don't really know how to fix it. Every time i try to play the game i get this error in unity: NullReferenceException: Object reference not set to an instance of an object PlayerAimWerpon.HandleAming () (at Assets/scripts/PlayerAimWerpon.cs:28) PlayerAimWerpon.Update () (at Assets/scripts/PlayerAimWerpon.cs:18) (although I dont get any error messages in VS) Here is fragment of code its having issues with private void Update(){ HandleAming(); } private void HandleAming() { Vector3 mousePosition = UtilsClass.GetMouseWorldPosition(); Vector3 aimDirection = (mousePosition - transform.position).normalized; float angle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg; aimTransform.eulerAngles = new Vector3(0, 0, angle); } }
📦 Check out the Grow your skills Mega Bundle here: assetstore.unity.com/mega-bundles/grow-your-skills?aid=1101l96nj&pubref=shootproj
🌐 Learn more about Unity Learn Premium here: unity.com/products/learn-premium?aid=1101l96nj&pubref=shootproj
❤️ Using this Affiliate Link helps support the channel
I making a fnaf fan game on unity and i can’t make a Good ai I did wander but well it traces the player it goes back to wandering and it’s been doing my head in can you help I only know C# and I’m learning python
Bro how can I get your library just like "using code monkey.utils;"
I can't watch your tutorial because of that. Plz help me bro, I am a big fan of Brackeys,blackthornprod and Dani. I wish you to be one of my idol bro plz help me with some kind of link thank you bro
Download the package and import it into your project unitycodemonkey.com/utils.php
You missed one method: instantiating bullets, and making raycasts from them to check if something within a certain range of the raycasts.
good tutorial! gj
There's another way to detect projectile collisions, which is ideal for if you want the projectile to travel very fast, but not be an instant-hit like how a raycast would accomplish.
Using the distance check or physics system can both occasionally allow projectiles to pass through targets if the projectile is traveling fast enough (even if you're using a rigidbody with continuous collision detection), causing something like this to happen...
[Projectile last frame] [Target] [Projectile current frame]
>===> (O) >===>
...Where the position of the projectile between the last and current frame is at a great enough distance to completely pass the target, never intersecting with it.
The trick to solve this is by having the projectile perform a raycast backwards to the position it was in on the previous frame, and detect if the raycast has intersected with anything, which would look like this:
[Projectile last frame] [Target] [Projectile current frame]
[x = raycast hit]
>===>------------------------(O)x------------------------>===>
So far, I've had a 100% success rate with very fast projectiles hitting targets using this method.
I've been searching for a RUclips video that showed this method with no luck (I think I saw it a year or two ago and only vaguely remembered it) so thank you so much for this comment
Do you have code example for this method?
@@bishopjackson2264 Been awhile since I worked with Unity, but it might look something like this:
public class Projectile : MonoBehaviour
{
[SerializeField] private RigidBody _projectileBody;
[SerializeField] private LayerMask _hitMask;
private Vector3 _lastFramePosition;
// Whenever this behaviour is first instantiated/re-enabled in the scene, ensure _lastFramePosition is up-to-date and initialize its body velocity.
void OnEnable()
{
UpdateLastFramePosition();
_projectileBody.velocity = transform.forward * 100
}
// Ensure _lastFramePosition is continuously updated every frame.
void Update() => UpdateLastFramePosition();
// Detect raycast hits every FixedUpdate step.
void FixedUpdate() => DetectRaycastHit();
void UpdateLastFramePosition() => _lastFramePostion = transform.position;
void DetectRaycastHit()
{
// Cast a ray from our current position to our previous position last frame.
if(Physics.LineCast(transform.position, _lastFramePosition, out RayCastHit hit, _hitMask))
{
// The raycast hit something - process the hit logic here.
}
}
}
@@Dxpress_ afaik lateupdate might work for this as well
Congrats on the unity sponsorship! great video
Thanks! It's great to be officially recognized!
I love how every action your character made you also include the tutorial on how to do said action, you truly are awesome
One of the variations on the first bullet would be to have a raycast from the last position to a new position to act as continuous collision substitution. That will allow fast non Rigidbody objects to test collision without checking all targets.
Hey, I've just made something similar for my own project and I have a few suggestions to your code. To instantiate the bullet you can write something like this:
Instantiate(Bullet, aim.position, aim.rotation);
And then in the Bullet class you only need to write:
void Start()
{
Destroy(gameObject, 5f);
}
// Update is called once per frame
void Update()
{
transform.position += transform.forward * Time.deltaTime * 100;
}
Wow! These videos are AWESOME. Thank you so much for taking the time to do provide this content. You are helping me finish my first game jam!
Looking good, shooting projectiles is so cool!
Hi there ! :D
@@457Deniz457 hey you! Enjoying some pew pew I see ;)
@@GabrielAguiarProd Haha yes ! :D
Thanks! The final visual does look surprisingly good, makes me want to use it to make a game like Enter the Gungeon
@@CodeMonkeyUnity Then do it ! :D
Excellent tutorial, as always. I'm keeping my fingers crossed that this channel becomes your sustainable source of income!
Hello,
another smart and clear video for those who have to stay home. Thank you so much !
Literally started to look for a video like this a week ago.
You good sir have earned yourself a new subscriber.
Please continue doing quick yet indepth videos like this one on small mechanics.
Your approach was perfect.
Wow,You are a real pro,Hard Work Pays
YOU ARE THE BEST MAN
I need the projectile to have new mechanics and components after upgrading. But adding components when creating the projectile is costly for mobile devices, in my opinion.
What are the pros and cons of using the transform method vs addForce method to move a projectile?
transform means no physics, easier to code no burden on the physic simulation if you have lots of projectile (i havent made the test).
Top quality video! Finally I 've fully understood what is a raycasthit! and like the video on the different types of collision, also this video explained in the simplest and clearest way possible the differences between all these methods...I'm very grateful to you!
I'm glad you found it helpful!
Just having a hard time trying to use this because of all the premade scripts
This. I'm trying to understand but with all the premade scripts, I'm lost with what and how
Yeah, he made it too complicated for newbies like myself.
There are some things you have to change like for the CharacterAim_Base I replaced it with my script that is for aiming which Is PlayerAimWeapon from his other videos
Same, I'm getting a bit lost trying to find all the references between scripts.
And I still don't understand why he's getting the Bullet component from the transformBullet...I mean, I'm trying to make it work but without the exact same structure, it's really hard to follow what's happening.
Even using the project files, I don't really understand what's happening and when I try to apply it to my own project, I can pass the shootdirection vector to the bullet script, but they default back to 0 once I use them in the update method.
I think I'm gonna have to follow another tutorial for this one.
It just sucks that it's the only one I can find that doesn't use rigidbodies and I really don't need physics for my project so I was hoping to implement that first technic.
if (target != null)
target.Damage();
Can be shortened to just:
Target?.Damage();
Not exactly, because Target inherits UnityEngine.Object it won't be exactly null. In this specific case the if statement is a must
for the readability sometimes using an if statement is better than using the '?', never knows who is gonna read the code, a lot of junior devs don't know what ? means or don't use it
CharacterAim_Base the type or namespacename could not be found pls help!
you must have tried to literally copy the whole script word for word
instead of doing that just copy the lines where the bullets are instantiated _inside_ a if statement, which checks wether a button is pressed or not
edit: nvm that wont work either because of how he intregrates those lines with his premade scripts
Thanks for the amazing tutorial as per usual! Keep em coming!
Great video, and I just realized that battlefield4 uses the ray cast hit detection method in 3d, I realized it when i shot a rocket in the game and no rocket spawned but there was still an explosion, funny that I was confused and thought the game was bugged, but now I can try and make it myself
Nice job!keep up the good work
this video was awesome thanks
Thanks for the tut. now i get it
big fan of you
great video!
just when I was thinking how to merge two lasers and form a third laser to emit the other way without having a hole in the middle.
this video enlightened me ~ thank you.
oh and what about using particle system for projectiles? Is it good or bad? cuz that seems to be the easiest...would I face problems using that in the long term?
Is it possible to use Trigger on the particle system?
How can I make a spread for bullets?
Fire multiple and apply an angle, so first bullet goes towards the target direction, second +10º, third -10º
The bullet trace continues past the target after it hits, would you need to modify the bullet trace class to make sure it stops when it hits the target?
You could do a Raycast from the ShootPoint towards the MousePosition and see what objects it hits, then use that for the Trace end point rather than the mouse position
Why there’s no particle system driven projectiles? In some cases, it is the easiest way.
Sure that's another approach. Personally I've never used it simply because transforms or rigidbodies already work great and I'm not very good at creating good looking VFX.
8:35 How could I get angle and make bullet go straight in a top down 3D game?
In 3D you can just use transform.LookAt to make a transform look directly at a point ruclips.net/video/FbM4CkqtOuA/видео.html
could you show how to shoot particle projectiles?
In the PlayerShoot class is it possible to pass the position of the target (from the BulletRaycast class if it hits something) so the weapon tracer doesn't go over the target if it hits it. Thanks for the awesome videos!
Yup that's what I did in my Third Person Shooter bullet, the bullet receives a target position and just moves towards it and destroys when it reaches ruclips.net/video/FbM4CkqtOuA/видео.html
Good video! I downloaded the project and my Unity ver: 2021.3.11f complained about 'using UnityEngine.Experimental.Rendering.light2D' . Most of the project works, but I am curious how to fix that. Thanks!
Nowadays its in UnityEngine.Rendering.Universal.Light2D
I see a problem with the transform and the physics solution:
When the bullet is fast and the target small the chance is very high that the bullet skips the target since position in Frame x is befor the target and in frame x+1 already behind it.
I solved that by checking every frame some space ahead with Physics.OverlapSphere() if the bullet is close enough to a target.
You can solve that by just setting the Rigidbody collision to Continuous instead of Discrete
@@CodeMonkeyUnity I am sure I tried that. But that was over three years ago...
@@CodeMonkeyUnity for anyone else that implements this sometime the continuous solution does not work other. I have very fast bullets and it can actually skip targets. So to fix this I do a raycast between previous position and curren position to see if anything is hit.
Awesome video! Will you also teach how you keep the CharacterAim_Base gunEndPointPosition updated?
I covered aiming towards the mouse here ruclips.net/video/fuGQFdhSPg4/видео.html
How can I apply rotation to the shootDir so the projectiles would be like a fixed shotgun pattern?
shootDir = Quaternion.Euler(0, 45, 0) * shootDir;
I want to do the method of the prefab bullet but I already have a script to use the "object pooler" I would not know how to put this same script to mine because you use your utilities,any help?
Not sure what you mean, an object pooler should be able to handle any prefab, doesn't matter what scripts are attached to it. What specific utility function are you referring to? There's nothing uniquely special about my utilities, you can easily write your own.
Hello sr. Im emiting an object that has vfx but it start small and increase by time to the wanted original size. How to emit it without the increase just original size?
Hey man, Can you cover how can we make Pooling System for our games?
The screen shake is so small and satisfying..how did u do that
Just moving the camera randomly a few units every frame for .1 seconds, check the GameHandler_Setup script in the project files
Great vide real helpful, though my bullet is going through the walls of my game, how can I fix it
Make sure Collision Detection is set to Continuous.
Alternatively use the Raycast method
if you dont mind, can you make a tutorial on creating goodlooking water 2d in unity.
Should have used the same asset so we could clearly see the differences...
I did use the exact same asset, what do you mean?
I have two problems, one problem is with the first method, my bullets speed are variable depending how close my mouse is to the player, the second is with the second method, because using add force make the bullets knockback enemies that also have a collider and a rigidbody.
Sounds like you need to normalize the movement vector, it shouldn't care about the distance to the mouse.
You can make the bullet a trigger if you want it to not impact enemies
@@CodeMonkeyUnity I am having the same first problem as Sanmiittai is having. My bullet is moving from shootEndPoint to mousePosition, not only that the speed is variable, the bullet also visually disappears at mouse position. I have the shootDir normalized, I can't seem to find what my issue is.
I found a solution to my problem, this solved my bullet speed and disappearing issue.
So for the fun of it, I decided to take a look at where on earth is my bullet flying off to and found that it was flying out of the camera view in Z.
I also did a Debug.Log of the shootDir which confirmed that indeed my bullet was ALSO moving in Z.
I simply zeroed the Z poisiton of mousePosition in the PlayerAimWeapon script by doing mousePosition.z = 0.
Hope this helps, it certainly helped me.
I'm having a hard time with the first one.
It works up to when I need to pass the shootDirection to the bullet script.
The vector looks correct in the Setup function but the default back to 0 in the update function.
Maybe you're never assigning the class field? If the parameter has the same name as the class field you need to do this.shootDirection = shootDirection to make sure you set it
@@CodeMonkeyUnity I found the issue! I completely forgot to pass along the instantiated bullet to the Setup function.
So, if I understand correctly (and I might not xD), I was accessing the values of the original prefab bullet at (0,0,0) rather than the values of the instantiated bullet.
edit = or rather, I was basically using the Transform values of the PlayerShoot script...I think.
i cant add a component to a prefab, it says i can only modify it through assetpostprocessor. why is this?
How about using particles as bullets???
Sure that's another approach. Personally I've never used it simply because transforms or rigidbodies already work great and I'm not very good at creating good looking VFX.
I know this has hit detection with the assumption on shooting projectiles, but what kind of hit detection would be best for button smashers that are just melee combat based?
Possibly just OverlapBox or a simple Distance query
ruclips.net/video/h9oEhVqGptU/видео.html
ruclips.net/video/AXkaqW3E9OI/видео.html
Hiya, the mega bundle says error code, not available. shame.
Yeah the Mega Bundle has ended, right now there's the Spring Sale though
Code Monkey, do you have video about controll characher in TopDown game?
I covered the character controller here ruclips.net/video/Bf_5qIt9Gr8/видео.html
Hey, uhm can you explain the CharacterAimBase please, I cant seem to find a video where you talk about it...
I covered weapon aiming here ruclips.net/video/fuGQFdhSPg4/видео.html
@@CodeMonkeyUnity is it the playeraimweapon script?
8:36 U can Just do transform.up = shootDir right?
Sure, either transform.up or transform.right depending on how it's set up
@code monkey, is there a way to combine the raycast methord with guninputpos, like the slower bullet to prevent fps reg issues? im still new to coding, but so far ive done a few scripts :D
I Cant Sign Up On Your Website
Why not? Check your spam folder for the validate link
@@CodeMonkeyUnity the links from this video
Never Mind I fixed it but the verification email wont come throw so i checked the email and its the right email
Would you be able to use the first two shooting methods when you're programming enemy AI?
Sure, the bullet doesn't care if its fired by the player or an AI enemy
Bro, I am making a 2d top down space shooter. There is a problem in shooting system, that is , when enemy is shooting and I shoot, then the player's bullet is colliding with enemy bullet and the player's bullet is destroyed but the enemies bullet is not destroyed. Can you tell me what to do to make the both bullets passing away without any collision.
If you want your player and enemy projectiles to not collide with eachother you can put them on different layers like “player projectile” and “enemy projectile” then use the collision matrix to turn off the collision of those 2 layers.
I get this weird thing with my GunEndPointPosition that makes it so when i shoot, the bulled starts at like -40x instead of x being 0. I have no clue of what im doing wrong. Help would be greatly appreciated.
Are you confusing localPosition and position?
Hi i have a question which is the best performant approach for a tower defense type of game that doesnt consume much processing with lots of bullets instantiated?
The most efficient would be using the Particle System with Raycast Hit Detection.
Alternatively use DOTS for your Bullets and Enemies.
@@CodeMonkeyUnity So many thanks sensei I'm still learning with dots :) I used your dots path finding system mix with game objects its pretty well but it would be much better if I will be able to do it in full ECS someday :)
What do I do to Raycast2D
I have an issue when using the first method where if I have my cursor on top of my player everything gets messed up, because it shoots from the gun endpoint at my mouse which is on my player, so essentially I shoot backwards. Is there a solution to this?
Nevermind, I had the event arg in the shoot script getting the mouse position not the endpoint position.
You can just add a simple check, if the click position is right on top of the player, don't fire the bullet
Is the collider in particle system any good for bullets?
Sure, you could use that as well
I work on a 2d platformer, only sideview. Are your options viable in this kind of scenario? I already have some code, but I have troubles with the bullets. They fly up instead away from the player, and I cant rotate them. But could your script work in my case?
Sure, the only difference would be if you wanted to add bullet drop. If not then the logic is exactly the same
@@CodeMonkeyUnity thanks, I will try it!
@@CodeMonkeyUnity But may I ask one more thing? Could you imagine, why my bullets fly up? I just want to understand why. I posted my code here;forum.unity.com/threads/bullets-fly-up.952832/
I am looking for a solution since yesterday, and I cant wrap my head around the fact, that the bullets fly up, or stay dead in track with vector3.forward
Hi there -- I'm totally stumped on a null reference I'm getting for the event. I started with the 2d character controller tutorial w/ dodge roll & dash, then the aim at mouse tutorial, and now trying to add the shooting. Aiming works fine as I can see from the debug.log of the angle I'm aiming at correctly.
The "object reference not set to an instance of an object" error triggers within HandleShooting() on this line: OnShoot?.Invoke(this, new OnShootEventArgs
Visual studio is not flagging any issues.
Within Unity I have an empty object for the Player (shell) with the logic attached (char controller, player aim weapon, and player shoot projectile scripts) then a child object capsule placeholder, and the only serialized field is for the projectile prefab's transform, which was dragged in. The projectile is an empty game object (shell) w the projectile script attached, and a child visual which is simply a square sprite scaled into a rectangle (aka my placeholder laser visual). Then I have the Aim empty gameobject as a child of the Player (shell) with a child game object for the sprite and another child empty gameobject for the GunEndPointPosition.
Save my sanity for +2,000 XP and eternal gratitude.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAimWeapon : MonoBehaviour
{
public event EventHandler OnShoot;
public class OnShootEventArgs : EventArgs
{
public Vector3 gunEndPointPosition;
public Vector3 shootPosition;
}
private Transform aimTransform;
private Transform aimGunEndPointTransform;
private Animator aimAnimator;
private void Awake()
{
aimTransform = transform.Find("Aim");
aimAnimator = aimTransform.GetComponent();
aimGunEndPointTransform = transform.Find("GunEndPointPosition");
}
private void Update()
{
HandleAiming();
HandleShooting();
}
private void HandleAiming()
{
Vector3 mousePosition = GetMouseWorldPosition();
Vector3 aimDirection = (mousePosition - transform.position).normalized;
float angle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg;
aimTransform.eulerAngles = new Vector3(0, 0, angle);
Debug.Log(angle);
}
private void HandleShooting()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePosition = GetMouseWorldPosition();
//aimAnimator.SetTrigger("Shoot");
OnShoot?.Invoke(this, new OnShootEventArgs
{
gunEndPointPosition = aimGunEndPointTransform.position,
shootPosition = mousePosition,
});
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShootProjectile : MonoBehaviour
{
[SerializeField] private Transform projectilePrefab;
private void Awake()
{
GetComponent().OnShoot += PlayerShootProjectile_OnShoot;
}
private void PlayerShootProjectile_OnShoot(object sender, PlayerAimWeapon.OnShootEventArgs e)
{
Transform projectileTransform = Instantiate(projectilePrefab, e.gunEndPointPosition, Quaternion.identity);
Vector3 shootDir = (e.shootPosition - e.gunEndPointPosition).normalized;
projectileTransform.GetComponent().Setup(shootDir);
}
}
I don't think this last script is involved in the error, but just in case.. this is the "Bullet" script from the video
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
private Vector3 shootDir;
public void Setup(Vector3 shootDir)
{
this.shootDir = shootDir;
}
private void Update()
{
float moveSpeed = 100f;
transform.position += moveSpeed * Time.deltaTime * shootDir;
}
}
How do you get the shoot direction to cast the raycast?
If you want to shoot towards the mouse then you do (mousePosition - playerPosition).normalized to get the direction vector.
Thank you for the answer!
I didnt know about the normalized part. I solved this just yesterday by doing ScreenToWorldPoint on the Input.mousePosition.
How expensive is it to cast such a Ray on every frame?
I need to check if the player would hit the enemy and if yes, then shoot him automaticly. Is raycasting a good solution or is it too expensive?
@@VladaPersonal A single ray is extremely cheap, you only have to worry about performance if you're firing thousands every frame.
I'm having a problem i can't understand
When i shoot, the bullet goes in the direction of the mouse compared to the center of the scene instead of the player position
Any ideia of how to solve this??? My code looks like is exactly to the one in the video
See how you're calculating the direction, use Debug.Log to see what the vector looks like and what is the player and mouse position
@@CodeMonkeyUnity So, it seems everything is exactly how it should be
Player Position and Mouse Position is following my movement right
The same goes with my AimDirection and ShootDir
And the Angle is rotating around me
I still don't get whats happening :\
I know that is old video but I have really weird problem my bullets don't fly flat my
I do a top down game (2D) and my shooting position have served 0 in rotation but bullet still don't fly flat
Any solution for this, some ideas
What do you mean by flat? It's moving in the Z axis? Check your logic to see what movement vector you're giving it
@@CodeMonkeyUnity yes in z Axis but with very small values something like 0.01 every second
@@kris007iron Add a Debug.Log(); to see how you are calculating the movement direction. In a 2D game the Z should always be 0
Coolio! 👍🤓
Hmm... does the collision system in Unity account for frame rate differences? I made a game in Java before and had to write my own code to account for that stuff. Would be nice to not have to do that.
Yes, in your rigidbody you can change the collision detection between Discrete where the object teleports to the next position and then checks for collisions
Or set it to Continuous and it will detect collisions between the start and end positions
3 ways to melee attack ?
youtube sucks, i search "projectiles in unity3d" and the first result is a unity2d tutorial
The logic is exactly the same, you just uses meshes instead of sprites ruclips.net/video/3zxTigjJr24/видео.html
Please teach us making this sort of toturials form scartch... request from mee
This is showing how to shoot projectiles from scratch.
For the character I covered it here ruclips.net/video/Bf_5qIt9Gr8/видео.html
The weapon aiming here ruclips.net/video/fuGQFdhSPg4/видео.html
@@CodeMonkeyUnity sorry I am new to your channel.. I clicked here so I thought you use ready made assets .. any way thanks for those videos
Make amionation tutorials
you mean animation
@@fedggg no amionation
You know weapons ammo thinks😂
dai craft I’m going to blame that on we’re I’m from
ammunition fam ^^
Bullet are too fast for collision and it is saying destroying object may cause loss data plz fix my problems
Edit = thank For reply but this are baby solutions and by the way I have already fix it my bullet speed. Was 3000 and it was going through wall so I want to destroy it on collision with other objects. So first I use trigger enter but unfortunately trigger enter unable to catch frame due to bullet high-speed So
i used raycast for collision detection of bullet
Set the collision detection to Continuous instead of Discrete
Or do a manual Raycast.
I am having such an issue with this. I have used the code exactly as it is and the bullets do not move, they just hover in the spawn location. Has anyone else had this issue?
Are you moving them with a rigidbody? Did you set the velocity? Make sure you're not spawning them inside a collider
Add some Debug.Log to make sure the code is running
@@CodeMonkeyUnity thanks for those tips, I will try them after work sometime this week. Got to a stage where even at work all I think about is my indie game dev projects and your videos alongside Thomas Brushes have helped a tonne.
How can I contact you because you can work with me in the future Because you are one of the geniuses that I want to join my team in the future all the best from anass i hope to reply me soon
Sorry I'm already way too busy and not available for freelance work.
I need some help with making my projectiles play a particle upon impact or destruction
You can make it a solid non-trigger bullet and use OnCollisionEnter2D which gives you a Collision that you can then use to get the contact points.
Thanks
How can i use CodeMonkey.Utils ???
Just download the package and import it into your project. It will add a folder with all the source files.
@@CodeMonkeyUnity I downloaded one unity package file, how can i import in my project, sorry i'm a beginner (thanks for the reply)
@@CodeMonkeyUnity i got the problem, sorry !
how do I get the endpoint?
In my case it's the mouse click position
@@CodeMonkeyUnity i meant where th bullet comes from
@@juicedup14 Oh that one depends on how you handle the weapon aiming. If you're rotating a game object you can use a invisible transform to position it ruclips.net/video/fuGQFdhSPg4/видео.html
In my case I also have an invisible point baked into my animations.
@@CodeMonkeyUnity thanks
Can you share what code you have in CharacterAim_Base script.
I covered weapon aiming here ruclips.net/video/fuGQFdhSPg4/видео.html
@@CodeMonkeyUnity One more thing I want to ask is can I use both raycast and instantiate methods for different guns in my game.
@@paritoshmishra2572 Sure, you can make a standard rifle that fires raycasts and a Rocket launcher that fires projectiles
I HAVE A HUGEEEEE ISSUE with firing the Gun, the bullet spawn lags behind just a small distance behind, no matter what direction I move in, depending on speed and height, like if I am running or Jumping, or just side strafing, the bullet spawnpoint shifts side to side, it sucks, please help. If you could point me in the right direction or offer your advice, I would be forever in your debt. So, Basically the bullets are spawning from where I was a second or so before, rather than from where I am. It makes the bullet spawnpoint to shift side to side, Help....Please.
Here is the code I am using
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public float speed = 80;
public GameObject bullet;
public Transform barrel;
public AudioSource audioSource;
public AudioClip audioClip;
public void Fire()
{
Instantiate(bullet, barrel.position, barrel.rotation).GetComponent().AddForce(barrel.forward * speed);
audioSource.PlayOneShot(audioClip);
Destroy(bullet, 2);
}
}
Where do you have the barrel position? Is the bullet rigidbody set to Interpolate?
I making a fnaf fan game on unity and i can’t make a Good ai I did wander but well it traces the player it goes back to wandering and it’s been doing my head in can you help I only know C# and I’m learning python
What do you want your AI to do? You need to answer that question in a more specific way than just "Good AI"
@@CodeMonkeyUnity i made it wander but i need it to chase the player not to damage the
player if it hits the player the player gets jump scared and sent to the title screen but my problem is i cant get the AI to wander and do chase in the same script
Sir please tell how to make a our own game and program
Start off by learning the basics here ruclips.net/video/E6A4WvsDeLE/видео.html
And then here ruclips.net/video/IFayQioG71A/видео.html
Video starts at 4:00
Can someone tell me that is this game was made in 2D or 3D please ?
This is in 2D but if you use 3D component then everything works almost exactly the same
I Need a 3d raycast
Then use Physics.Raycast(); instead of Physics2D
@@CodeMonkeyUnity Thanks
dont work
What doesn't work?
using CodeMonkey; using CodeMonkey.Utils; ??
Those are the namespaces for my utilities that you can download from the website
my problem with rigidbody bullets are that OnCollisionEnter work too slow. when my bullet hit something after 1sec. the effect appears
OnCollisionEnter is triggered when the Physics System updates so if you leave the FixedUpdate at the default of 50 times per second then at the most it will take 20ms
If it is indeed delayed by 1 second then the issue is not with OnCollisionEnter
3:13
Can you replay of all the codes in this vid I don’t really have time to write and sorry if I bothered you
can you do 3D xD
Most things I show in these videos are usable both in 2D and 3D ruclips.net/video/3zxTigjJr24/видео.html
@@CodeMonkeyUnity Oh sorry
get to to the freaking point man
What do you mean? What part do you feel I dragged on unnecessarily?
@@CodeMonkeyUnity well, the intro was long and basically duplicate. You have went through the same routine twice. Explaining why you are making the video sponsered content into explaining why you make the video into sponsered content. I know what the video is about, I clicked the thumbnail. If the actual content is not withinthe first minute I lose intrest. I am happy that you asked and did not just ignore my rather crude response
uninstall
how a can use the librery "using CodeMonkey.utils" thats librery unity doesn have
That's my own utilities, you can download the source code from the website, or just write the code yourself
Transform bulletTransform = Instantiate(Bullet, ToFirePoint , Quaternion.identity
show to me
Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Transform'
You defined Bullet as a GameObject which means the Instantiate(); function will return a GameObject and not a Transform
either change Bullet to Transform or call Instantiate().transform
@@CodeMonkeyUnity thanks it worked
Really usefull video but i have issue and i don't really know how to fix it.
Every time i try to play the game i get this error in unity:
NullReferenceException: Object reference not set to an instance of an object
PlayerAimWerpon.HandleAming () (at Assets/scripts/PlayerAimWerpon.cs:28)
PlayerAimWerpon.Update () (at Assets/scripts/PlayerAimWerpon.cs:18)
(although I dont get any error messages in VS)
Here is fragment of code its having issues with
private void Update(){
HandleAming();
}
private void HandleAming()
{
Vector3 mousePosition = UtilsClass.GetMouseWorldPosition();
Vector3 aimDirection = (mousePosition - transform.position).normalized;
float angle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg;
aimTransform.eulerAngles = new Vector3(0, 0, angle);
}
}
Use Debug.Log to find what is null ruclips.net/video/5irv30-bTJw/видео.html