3 Ways to Shoot Projectiles in Unity!

  Рет қаралды 237,577

Code Monkey

Code Monkey

4 жыл бұрын

✅ Get the Project files and Utilities at unitycodemonkey.com/video.php...
🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses
Let's check out 3 Ways of Shooting Projectiles and 3 Ways of doing Hit Detection. Transform, Physics and Raycast.
Learn Unity in 17 MINUTES!
• Learn Unity in 17 MINU...
Learn C# BASICS in 10 MINUTES!
• Learn C# BASICS in 10 ...
• C# Basics to Advanced
🌐 Get the Mega Bundle worth over $1000 for 90% off at assetstore.unity.com/?on_sale...
❤️ Using this Affiliate Link helps support the channel
Sponsored by Unity
Character Controller in Unity 2D! (Move, Dodge, Dash)
• Character Controller i...
Aim at Mouse in Unity 2D
• Aim at Mouse in Unity ...
Make Awesome Effects with Meshes in Unity | How to make a Mesh
• How to make a Mesh in ...
Sprite Outline (Animated!) - 2D Shader Graph Tutorial
• Sprite Outline (Animat...
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials / @codemonkeyunity
See you next time!
📍 Support on Patreon / unitycodemonkey
🤖 Join the Community Discord / discord
📦 Grab the Game Bundle at unitycodemonkey.com/gameBundl...
📝 Get the Code Monkey Utilities at unitycodemonkey.com/utils.php
#unitytutorial #unity3d #unity2d
--------------------------------------------------------------------
Hello and welcome, I am your Code Monkey and here you will learn everything about Game Development in Unity 2D using C#.
I've been developing games for several years with 7 published games on Steam and now I'm sharing my knowledge to help you on your own game development journey.
You can see my games at www.endlessloopstudios.com
--------------------------------------------------------------------
- Website: unitycodemonkey.com/
- Twitter: / unitycodemonkey
- Facebook: / unitycodemonkey

Пікірлер: 225
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
📦 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
@fedggg
@fedggg 4 жыл бұрын
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
@mmgame-devacademy3799
@mmgame-devacademy3799 4 жыл бұрын
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
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Download the package and import it into your project unitycodemonkey.com/utils.php
@klarnorbert
@klarnorbert 4 жыл бұрын
You missed one method: instantiating bullets, and making raycasts from them to check if something within a certain range of the raycasts.
@devsmartnothard530
@devsmartnothard530 2 жыл бұрын
good tutorial! gj
@trunghieuam4493
@trunghieuam4493 2 жыл бұрын
I love how every action your character made you also include the tutorial on how to do said action, you truly are awesome
@Dxpress_
@Dxpress_ 4 жыл бұрын
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.
@KerupukKeju
@KerupukKeju Жыл бұрын
I've been searching for a KZbin 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
@bishopjackson2264 Жыл бұрын
Do you have code example for this method?
@Dxpress_
@Dxpress_ Жыл бұрын
@@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. } } }
@plinyvicgames
@plinyvicgames Жыл бұрын
@@Dxpress_ afaik lateupdate might work for this as well
@quarantinethis8981
@quarantinethis8981 2 жыл бұрын
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.
@aquaarmour4924
@aquaarmour4924 4 жыл бұрын
Congrats on the unity sponsorship! great video
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Thanks! It's great to be officially recognized!
@Analogity
@Analogity 3 жыл бұрын
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!
@jean-michel.houbre
@jean-michel.houbre 4 жыл бұрын
Hello, another smart and clear video for those who have to stay home. Thank you so much !
@leagueoflags
@leagueoflags 4 жыл бұрын
Excellent tutorial, as always. I'm keeping my fingers crossed that this channel becomes your sustainable source of income!
@NeZversSounds
@NeZversSounds 3 жыл бұрын
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.
@DeadalusX
@DeadalusX 2 жыл бұрын
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; }
@erz3030
@erz3030 4 жыл бұрын
Thanks for the amazing tutorial as per usual! Keep em coming!
@kken8766
@kken8766 4 жыл бұрын
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?
@hamzamusani5500
@hamzamusani5500 3 жыл бұрын
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
@CodesnippetBiz
@CodesnippetBiz 3 жыл бұрын
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!
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
I'm glad you found it helpful!
@GabrielAguiarProd
@GabrielAguiarProd 4 жыл бұрын
Looking good, shooting projectiles is so cool!
@457Deniz457
@457Deniz457 4 жыл бұрын
Hi there ! :D
@GabrielAguiarProd
@GabrielAguiarProd 4 жыл бұрын
​@@457Deniz457 hey you! Enjoying some pew pew I see ;)
@457Deniz457
@457Deniz457 4 жыл бұрын
@@GabrielAguiarProd Haha yes ! :D
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Thanks! The final visual does look surprisingly good, makes me want to use it to make a game like Enter the Gungeon
@457Deniz457
@457Deniz457 4 жыл бұрын
@@CodeMonkeyUnity Then do it ! :D
@armaankeshava8471
@armaankeshava8471 4 жыл бұрын
Nice job!keep up the good work
@hasnainfareed8555
@hasnainfareed8555 3 жыл бұрын
Wow,You are a real pro,Hard Work Pays
@monsieuralexandergulbu3678
@monsieuralexandergulbu3678 3 жыл бұрын
Thanks for the tut. now i get it
@hyjalonfire
@hyjalonfire 4 жыл бұрын
this video was awesome thanks
@matebliadze4425
@matebliadze4425 11 ай бұрын
YOU ARE THE BEST MAN
@tintlost2160
@tintlost2160 3 жыл бұрын
@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
@manjunathj9202
@manjunathj9202 4 жыл бұрын
What are the pros and cons of using the transform method vs addForce method to move a projectile?
@wassilchoujaa3478
@wassilchoujaa3478 3 жыл бұрын
transform means no physics, easier to code no burden on the physic simulation if you have lots of projectile (i havent made the test).
@kutanarcanakgul5533
@kutanarcanakgul5533 4 жыл бұрын
Hey man, Can you cover how can we make Pooling System for our games?
@armandmorariu6
@armandmorariu6 4 жыл бұрын
Awesome video! Will you also teach how you keep the CharacterAim_Base gunEndPointPosition updated?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
I covered aiming towards the mouse here kzbin.info/www/bejne/nKaqgnmanbiDnZY
@Oxmond
@Oxmond 4 жыл бұрын
Coolio! 👍🤓
@PointToBlank89
@PointToBlank89 2 жыл бұрын
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!
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
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 kzbin.info/www/bejne/fJOwZXahptmCq6M
@magnusm4
@magnusm4 Жыл бұрын
Is it possible to use Trigger on the particle system?
@Thesupperals
@Thesupperals 3 жыл бұрын
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?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Possibly just OverlapBox or a simple Distance query kzbin.info/www/bejne/nmrSdpuMpqyjqrc kzbin.info/www/bejne/d4nOkqSNaKpshas
@TalhaRiaz197
@TalhaRiaz197 3 жыл бұрын
big fan of you
@flyingroads3498
@flyingroads3498 2 жыл бұрын
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?
@perssontm1628
@perssontm1628 4 жыл бұрын
Just having a hard time trying to use this because of all the premade scripts
@casoozh
@casoozh 3 жыл бұрын
This. I'm trying to understand but with all the premade scripts, I'm lost with what and how
@victorrus01
@victorrus01 3 жыл бұрын
Yeah, he made it too complicated for newbies like myself.
@Val-tt7yx
@Val-tt7yx Жыл бұрын
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
@RomainDelmaire
@RomainDelmaire Жыл бұрын
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.
@GARTZ09
@GARTZ09 3 жыл бұрын
if you dont mind, can you make a tutorial on creating goodlooking water 2d in unity.
@yifengchen5274
@yifengchen5274 4 жыл бұрын
Is the collider in particle system any good for bullets?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Sure, you could use that as well
@In-N-Out333
@In-N-Out333 4 жыл бұрын
if (target != null) target.Damage(); Can be shortened to just: Target?.Damage();
@sagiziv927
@sagiziv927 4 жыл бұрын
Not exactly, because Target inherits UnityEngine.Object it won't be exactly null. In this specific case the if statement is a must
@eheh5748
@eheh5748 4 жыл бұрын
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
@carver8609
@carver8609 4 жыл бұрын
CharacterAim_Base the type or namespacename could not be found pls help!
@not_herobrine3752
@not_herobrine3752 3 жыл бұрын
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
@unreal-illia
@unreal-illia 4 жыл бұрын
Code Monkey, do you have video about controll characher in TopDown game?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
I covered the character controller here kzbin.info/www/bejne/eJfCZqR_qZ56qJo
@physicschaosdev
@physicschaosdev Жыл бұрын
could you show how to shoot particle projectiles?
@ez4novi
@ez4novi 4 жыл бұрын
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
@CodeMonkeyUnity 4 жыл бұрын
The most efficient would be using the Particle System with Raycast Hit Detection. Alternatively use DOTS for your Bullets and Enemies.
@ez4novi
@ez4novi 4 жыл бұрын
@@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 :)
@DerriStudios6969
@DerriStudios6969 3 жыл бұрын
Would you be able to use the first two shooting methods when you're programming enemy AI?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Sure, the bullet doesn't care if its fired by the player or an AI enemy
@mr.mistake8753
@mr.mistake8753 4 жыл бұрын
i cant add a component to a prefab, it says i can only modify it through assetpostprocessor. why is this?
@mcleverm01
@mcleverm01 Жыл бұрын
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!
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
Nowadays its in UnityEngine.Rendering.Universal.Light2D
@studenthtw-gamedesign5826
@studenthtw-gamedesign5826 3 жыл бұрын
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
@CodeMonkeyUnity 3 жыл бұрын
Sure, the only difference would be if you wanted to add bullet drop. If not then the logic is exactly the same
@studenthtw-gamedesign5826
@studenthtw-gamedesign5826 3 жыл бұрын
@@CodeMonkeyUnity thanks, I will try it!
@studenthtw-gamedesign5826
@studenthtw-gamedesign5826 3 жыл бұрын
@@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
@KingKafei
@KingKafei Жыл бұрын
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?
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
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
@vikke5123
@vikke5123 2 жыл бұрын
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.
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Are you confusing localPosition and position?
@lennyseed9255
@lennyseed9255 3 жыл бұрын
Great vide real helpful, though my bullet is going through the walls of my game, how can I fix it
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Make sure Collision Detection is set to Continuous. Alternatively use the Raycast method
@Deathkid0990
@Deathkid0990 4 жыл бұрын
What do I do to Raycast2D
@SirGilbert_
@SirGilbert_ Жыл бұрын
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?
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
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.
@yashwanthd1998
@yashwanthd1998 4 жыл бұрын
The screen shake is so small and satisfying..how did u do that
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Just moving the camera randomly a few units every frame for .1 seconds, check the GameHandler_Setup script in the project files
@hoangminhnguyen9571
@hoangminhnguyen9571 2 жыл бұрын
8:35 How could I get angle and make bullet go straight in a top down 3D game?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
In 3D you can just use transform.LookAt to make a transform look directly at a point kzbin.info/www/bejne/fJOwZXahptmCq6M
@endline7945
@endline7945 4 жыл бұрын
How can I make a spread for bullets?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Fire multiple and apply an angle, so first bullet goes towards the target direction, second +10º, third -10º
@MarkJrLuat
@MarkJrLuat 3 жыл бұрын
Hey, uhm can you explain the CharacterAimBase please, I cant seem to find a video where you talk about it...
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
I covered weapon aiming here kzbin.info/www/bejne/nKaqgnmanbiDnZY
@MarkJrLuat
@MarkJrLuat 3 жыл бұрын
@@CodeMonkeyUnity is it the playeraimweapon script?
@RomainDelmaire
@RomainDelmaire Жыл бұрын
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.
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
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
@RomainDelmaire
@RomainDelmaire Жыл бұрын
@@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.
@manuelg8050
@manuelg8050 4 жыл бұрын
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
@CodeMonkeyUnity 4 жыл бұрын
You can solve that by just setting the Rigidbody collision to Continuous instead of Discrete
@manuelg8050
@manuelg8050 4 жыл бұрын
@@CodeMonkeyUnity I am sure I tried that. But that was over three years ago...
@christian2809
@christian2809 2 жыл бұрын
@@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.
@davidcalderwood7041
@davidcalderwood7041 Жыл бұрын
How can I apply rotation to the shootDir so the projectiles would be like a fixed shotgun pattern?
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
shootDir = Quaternion.Euler(0, 45, 0) * shootDir;
@David-vz4yk
@David-vz4yk 4 жыл бұрын
I need some help with making my projectiles play a particle upon impact or destruction
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
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.
@David-vz4yk
@David-vz4yk 4 жыл бұрын
Thanks
@StupendousStudios-bg4yy
@StupendousStudios-bg4yy Жыл бұрын
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; } }
@pierceblk6838
@pierceblk6838 Жыл бұрын
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?
@pierceblk6838
@pierceblk6838 Жыл бұрын
Nevermind, I had the event arg in the shoot script getting the mouse position not the endpoint position.
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
You can just add a simple check, if the click position is right on top of the player, don't fire the bullet
@CottidaeSEA
@CottidaeSEA 4 жыл бұрын
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.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
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
@Void-rd1nh
@Void-rd1nh 4 жыл бұрын
Could you make a tutorial to show how to make a 2d shooter game with like enemies running at you and you shoot them in a 2d game.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
I made a complete Top Down Shooter game here kzbin.info/www/bejne/e6rbZHicptaZg9k
@dragonballz3686
@dragonballz3686 2 жыл бұрын
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.
@galexyofthings
@galexyofthings 2 жыл бұрын
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.
@kawaikami
@kawaikami 4 жыл бұрын
Why there’s no particle system driven projectiles? In some cases, it is the easiest way.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
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.
@StarrkrinGamer
@StarrkrinGamer Жыл бұрын
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.
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
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
@dodle
@dodle Жыл бұрын
@@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.
@dodle
@dodle Жыл бұрын
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.
@VladaPersonal
@VladaPersonal 3 жыл бұрын
How do you get the shoot direction to cast the raycast?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
If you want to shoot towards the mouse then you do (mousePosition - playerPosition).normalized to get the direction vector.
@VladaPersonal
@VladaPersonal 3 жыл бұрын
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?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
@@VladaPersonal A single ray is extremely cheap, you only have to worry about performance if you're firing thousands every frame.
@paritoshmishra2572
@paritoshmishra2572 3 жыл бұрын
Can you share what code you have in CharacterAim_Base script.
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
I covered weapon aiming here kzbin.info/www/bejne/nKaqgnmanbiDnZY
@paritoshmishra2572
@paritoshmishra2572 3 жыл бұрын
@@CodeMonkeyUnity One more thing I want to ask is can I use both raycast and instantiate methods for different guns in my game.
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
@@paritoshmishra2572 Sure, you can make a standard rifle that fires raycasts and a Rocket launcher that fires projectiles
@TheJobKnockey
@TheJobKnockey 3 жыл бұрын
Good tutorial, my only complaint is when you do stuff and don't show it or make it so you have to head to another video to finish the tutorial
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
What didn't I show?
@kris007iron
@kris007iron 3 жыл бұрын
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
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
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
@kris007iron
@kris007iron 3 жыл бұрын
@@CodeMonkeyUnity yes in z Axis but with very small values something like 0.01 every second
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
@@kris007iron Add a Debug.Log(); to see how you are calculating the movement direction. In a 2D game the Z should always be 0
@victorgomes9985
@victorgomes9985 3 жыл бұрын
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
@CodeMonkeyUnity 3 жыл бұрын
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
@victorgomes9985
@victorgomes9985 3 жыл бұрын
@@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 :\
@hanavargas666
@hanavargas666 4 жыл бұрын
How about using particles as bullets???
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
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.
@dalegriffiths3628
@dalegriffiths3628 4 жыл бұрын
Hiya, the mega bundle says error code, not available. shame.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Yeah the Mega Bundle has ended, right now there's the Spring Sale though
@fedggg
@fedggg 4 жыл бұрын
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
@CodeMonkeyUnity 4 жыл бұрын
What do you want your AI to do? You need to answer that question in a more specific way than just "Good AI"
@fedggg
@fedggg 4 жыл бұрын
@@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
@somerandomguy2892
@somerandomguy2892 3 жыл бұрын
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); } }
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Where do you have the barrel position? Is the bullet rigidbody set to Interpolate?
@animeoffighter8362
@animeoffighter8362 4 жыл бұрын
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
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Sorry I'm already way too busy and not available for freelance work.
@aero7982
@aero7982 3 жыл бұрын
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
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Set the collision detection to Continuous instead of Discrete Or do a manual Raycast.
@vixexxfn2068
@vixexxfn2068 3 жыл бұрын
I Cant Sign Up On Your Website
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Why not? Check your spam folder for the validate link
@vixexxfn2068
@vixexxfn2068 3 жыл бұрын
@@CodeMonkeyUnity the links from this video
@vixexxfn2068
@vixexxfn2068 3 жыл бұрын
Never Mind I fixed it but the verification email wont come throw so i checked the email and its the right email
@user-ir1hj5zb8z
@user-ir1hj5zb8z 4 жыл бұрын
3 ways to melee attack ?
@YTSHANKY
@YTSHANKY 3 жыл бұрын
Please teach us making this sort of toturials form scartch... request from mee
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
This is showing how to shoot projectiles from scratch. For the character I covered it here kzbin.info/www/bejne/eJfCZqR_qZ56qJo The weapon aiming here kzbin.info/www/bejne/nKaqgnmanbiDnZY
@YTSHANKY
@YTSHANKY 3 жыл бұрын
@@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
@juicedup14
@juicedup14 3 жыл бұрын
how do I get the endpoint?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
In my case it's the mouse click position
@juicedup14
@juicedup14 3 жыл бұрын
@@CodeMonkeyUnity i meant where th bullet comes from
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
​@@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 kzbin.info/www/bejne/nKaqgnmanbiDnZY In my case I also have an invisible point baked into my animations.
@juicedup14
@juicedup14 3 жыл бұрын
@@CodeMonkeyUnity thanks
@bts-vz2wu
@bts-vz2wu 3 жыл бұрын
Sir please tell how to make a our own game and program
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Start off by learning the basics here kzbin.info/www/bejne/e2ekZYqsqKmYgqc And then here kzbin.info/www/bejne/f3fEqoSfpKxqZ6M
@manderm
@manderm Жыл бұрын
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?
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
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
@manderm
@manderm Жыл бұрын
@@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.
@gyorfiendre6867
@gyorfiendre6867 3 жыл бұрын
How can i use CodeMonkey.Utils ???
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Just download the package and import it into your project. It will add a folder with all the source files.
@gyorfiendre6867
@gyorfiendre6867 3 жыл бұрын
@@CodeMonkeyUnity I downloaded one unity package file, how can i import in my project, sorry i'm a beginner (thanks for the reply)
@gyorfiendre6867
@gyorfiendre6867 3 жыл бұрын
@@CodeMonkeyUnity i got the problem, sorry !
@DuyTran-ss4lu
@DuyTran-ss4lu 4 жыл бұрын
Can someone tell me that is this game was made in 2D or 3D please ?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
This is in 2D but if you use 3D component then everything works almost exactly the same
@mr-spoon
@mr-spoon 4 жыл бұрын
Make amionation tutorials
@fedggg
@fedggg 4 жыл бұрын
you mean animation
@mr-spoon
@mr-spoon 4 жыл бұрын
@@fedggg no amionation You know weapons ammo thinks😂
@fedggg
@fedggg 4 жыл бұрын
dai craft I’m going to blame that on we’re I’m from
@gianpaolopascotto8248
@gianpaolopascotto8248 4 жыл бұрын
ammunition fam ^^
@5252emre
@5252emre 3 жыл бұрын
my problem with rigidbody bullets are that OnCollisionEnter work too slow. when my bullet hit something after 1sec. the effect appears
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
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
@Deathkid0990
@Deathkid0990 4 жыл бұрын
I Need a 3d raycast
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Then use Physics.Raycast(); instead of Physics2D
@Deathkid0990
@Deathkid0990 4 жыл бұрын
@@CodeMonkeyUnity Thanks
@MKHideOut
@MKHideOut 3 жыл бұрын
Should have used the same asset so we could clearly see the differences...
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
I did use the exact same asset, what do you mean?
@obesefrogman
@obesefrogman 2 жыл бұрын
3:13
@somedooby
@somedooby 2 жыл бұрын
Video starts at 4:00
@wizzkw5921
@wizzkw5921 3 жыл бұрын
Can you replay of all the codes in this vid I don’t really have time to write and sorry if I bothered you
@g5haco
@g5haco 3 жыл бұрын
can you do 3D xD
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Most things I show in these videos are usable both in 2D and 3D kzbin.info/www/bejne/aavbhZydn6-laJY
@g5haco
@g5haco 3 жыл бұрын
@@CodeMonkeyUnity Oh sorry
@wonderflounium
@wonderflounium 3 жыл бұрын
youtube sucks, i search "projectiles in unity3d" and the first result is a unity2d tutorial
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
The logic is exactly the same, you just uses meshes instead of sprites kzbin.info/www/bejne/aavbhZydn6-laJY
@s1pooky580
@s1pooky580 3 жыл бұрын
dont work
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
What doesn't work?
@brahimbelmouhand9888
@brahimbelmouhand9888 3 жыл бұрын
using CodeMonkey; using CodeMonkey.Utils; ??
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Those are the namespaces for my utilities that you can download from the website
@motimimon1
@motimimon1 3 жыл бұрын
get to to the freaking point man
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
What do you mean? What part do you feel I dragged on unnecessarily?
@motimimon1
@motimimon1 3 жыл бұрын
@@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
@mateuszkowalczyk2149
@mateuszkowalczyk2149 2 жыл бұрын
uninstall
@gamingtech1934
@gamingtech1934 10 ай бұрын
Transform bulletTransform = Instantiate(Bullet, ToFirePoint , Quaternion.identity show to me Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Transform'
@CodeMonkeyUnity
@CodeMonkeyUnity 10 ай бұрын
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
@gamingtech1934
@gamingtech1934 10 ай бұрын
@@CodeMonkeyUnity thanks it worked
@thomasyael1268
@thomasyael1268 Жыл бұрын
how a can use the librery "using CodeMonkey.utils" thats librery unity doesn have
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
That's my own utilities, you can download the source code from the website, or just write the code yourself
@DAX_V
@DAX_V 3 жыл бұрын
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); } }
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Use Debug.Log to find what is null kzbin.info/www/bejne/a5rVp2ZmYseHgNk
Modular Character System in Unity (Move, Attack, AI, Pathfinding)
21:16
3 Ways to Find Targets in Unity! (Collider, Physics, Distance)
15:41
Don’t take steroids ! 🙏🙏
00:16
Tibo InShape
Рет қаралды 29 МЛН
Follow @karina-kola please 🙏🥺
00:21
Andrey Grechka
Рет қаралды 13 МЛН
How Beginners can make games FAST!
9:59
Code Monkey
Рет қаралды 22 М.
How to make 2D GLOW in Unity!
15:56
Brackeys
Рет қаралды 578 М.
20 Advanced Coding Tips For Big Unity Projects
22:23
Tesseract
Рет қаралды 146 М.
What happened in Game Dev, Tech and Gaming?
18:14
Code Monkey
Рет қаралды 20 М.
How to Code (almost) Any Feature
9:48
DaFluffyPotato
Рет қаралды 627 М.
Scriptable Objects: What are they? How do you use them?
10:38
Unity 6 Preview is OUT!
4:09
Code Monkey
Рет қаралды 42 М.
How I Started Making Games with No Experience
9:49
Vimlark
Рет қаралды 1,9 МЛН
SHOOTING with BULLETS + CUSTOM PROJECTILES || Unity 3D Tutorial (#1)
9:25
Dave / GameDevelopment
Рет қаралды 188 М.
If You Can't Make Games After This Video, Give Up
4:37
Fredyy
Рет қаралды 695 М.
Don’t take steroids ! 🙏🙏
00:16
Tibo InShape
Рет қаралды 29 МЛН