3 Ways to Shoot Projectiles in Unity!

✅ 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

Пікірлер: 226

  • @CodeMonkeyUnity
    @CodeMonkeyUnity4 жыл бұрын

    📦 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

  • @aquaarmour4924
    @aquaarmour49244 жыл бұрын

    Congrats on the unity sponsorship! great video

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Thanks! It's great to be officially recognized!

  • @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 KZread 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

  • @trunghieuam4493
    @trunghieuam44932 жыл бұрын

    I love how every action your character made you also include the tutorial on how to do said action, you truly are awesome

  • @Analogity
    @Analogity3 жыл бұрын

    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.houbre4 жыл бұрын

    Hello, another smart and clear video for those who have to stay home. Thank you so much !

  • @quarantinethis8981
    @quarantinethis89812 жыл бұрын

    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.

  • @NeZversSounds
    @NeZversSounds4 жыл бұрын

    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.

  • @leagueoflags
    @leagueoflags4 жыл бұрын

    Excellent tutorial, as always. I'm keeping my fingers crossed that this channel becomes your sustainable source of income!

  • @GabrielAguiarProd
    @GabrielAguiarProd4 жыл бұрын

    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
    @armaankeshava84714 жыл бұрын

    Nice job!keep up the good work

  • @CodesnippetBiz
    @CodesnippetBiz4 жыл бұрын

    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

    4 жыл бұрын

    I'm glad you found it helpful!

  • @hasnainfareed8555
    @hasnainfareed85554 жыл бұрын

    Wow,You are a real pro,Hard Work Pays

  • @hamzamusani5500
    @hamzamusani55003 жыл бұрын

    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

  • @DeadalusX
    @DeadalusX2 жыл бұрын

    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; }

  • @hyjalonfire
    @hyjalonfire4 жыл бұрын

    this video was awesome thanks

  • @kken8766
    @kken87664 жыл бұрын

    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?

  • @monsieuralexandergulbu3678
    @monsieuralexandergulbu36783 жыл бұрын

    Thanks for the tut. now i get it

  • @matebliadze4425
    @matebliadze4425 Жыл бұрын

    YOU ARE THE BEST MAN

  • @erz3030
    @erz30304 жыл бұрын

    Thanks for the amazing tutorial as per usual! Keep em coming!

  • @Oxmond
    @Oxmond4 жыл бұрын

    Coolio! 👍🤓

  • @perssontm1628
    @perssontm16284 жыл бұрын

    Just having a hard time trying to use this because of all the premade scripts

  • @casoozh

    @casoozh

    4 жыл бұрын

    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.

  • @manjunathj9202
    @manjunathj92024 жыл бұрын

    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).

  • @armandmorariu6
    @armandmorariu64 жыл бұрын

    Awesome video! Will you also teach how you keep the CharacterAim_Base gunEndPointPosition updated?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    I covered aiming towards the mouse here kzread.info/dash/bejne/mKl7s6idmLa2l5c.html

  • @TalhaRiaz197
    @TalhaRiaz1973 жыл бұрын

    big fan of you

  • @carver8609
    @carver86094 жыл бұрын

    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

  • @tintlost2160
    @tintlost21603 жыл бұрын

    @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

  • @kutanarcanakgul5533
    @kutanarcanakgul55334 жыл бұрын

    Hey man, Can you cover how can we make Pooling System for our games?

  • @flyingroads3498
    @flyingroads34982 жыл бұрын

    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?

  • @wolffin4422
    @wolffin4422Ай бұрын

    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.

  • @endline7945
    @endline79454 жыл бұрын

    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º

  • @mr.mistake8753
    @mr.mistake87534 жыл бұрын

    i cant add a component to a prefab, it says i can only modify it through assetpostprocessor. why is this?

  • @In-N-Out333
    @In-N-Out3334 жыл бұрын

    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

  • @PointToBlank89
    @PointToBlank892 жыл бұрын

    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 kzread.info/dash/bejne/eJaBlqWkode1paQ.html

  • @unreal-illia
    @unreal-illia4 жыл бұрын

    Code Monkey, do you have video about controll characher in TopDown game?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    I covered the character controller here kzread.info/dash/bejne/dJqTl9OCpJytops.html

  • @GARTZ09
    @GARTZ093 жыл бұрын

    if you dont mind, can you make a tutorial on creating goodlooking water 2d in unity.

  • @hoangminhnguyen9571
    @hoangminhnguyen95712 жыл бұрын

    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 kzread.info/dash/bejne/eJaBlqWkode1paQ.html

  • @magnusm4
    @magnusm4 Жыл бұрын

    Is it possible to use Trigger on the particle system?

  • @Thesupperals
    @Thesupperals3 жыл бұрын

    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 kzread.info/dash/bejne/mm2jp8qPoarWpLg.html kzread.info/dash/bejne/c4yfw9OQY6iff6w.html

  • @physicschaosdev
    @physicschaosdev Жыл бұрын

    could you show how to shoot particle projectiles?

  • @vikke5123
    @vikke51232 жыл бұрын

    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?

  • @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.

  • @yifengchen5274
    @yifengchen52744 жыл бұрын

    Is the collider in particle system any good for bullets?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Sure, you could use that as well

  • @kawaikami
    @kawaikami4 жыл бұрын

    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.

  • @DerriStudios6969
    @DerriStudios69693 жыл бұрын

    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

  • @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

  • @yashwanthd1998
    @yashwanthd19984 жыл бұрын

    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

  • @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;

  • @Void-rd1nh
    @Void-rd1nh4 жыл бұрын

    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 kzread.info/dash/bejne/d62slaefodTMfdo.html

  • @ez4novi
    @ez4novi4 жыл бұрын

    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 :)

  • @lennyseed9255
    @lennyseed92553 жыл бұрын

    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

  • @pierceblk6838
    @pierceblk68382 жыл бұрын

    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

    2 жыл бұрын

    Nevermind, I had the event arg in the shoot script getting the mouse position not the endpoint position.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    You can just add a simple check, if the click position is right on top of the player, don't fire the bullet

  • @studenthtw-gamedesign5826
    @studenthtw-gamedesign58264 жыл бұрын

    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

    4 жыл бұрын

    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

    4 жыл бұрын

    @@CodeMonkeyUnity thanks, I will try it!

  • @studenthtw-gamedesign5826

    @studenthtw-gamedesign5826

    4 жыл бұрын

    @@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

  • @dragonballz3686
    @dragonballz36862 жыл бұрын

    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.

  • @MarkJrLuat
    @MarkJrLuat3 жыл бұрын

    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 kzread.info/dash/bejne/mKl7s6idmLa2l5c.html

  • @MarkJrLuat

    @MarkJrLuat

    3 жыл бұрын

    @@CodeMonkeyUnity is it the playeraimweapon script?

  • @hanavargas666
    @hanavargas6664 жыл бұрын

    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.

  • @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

  • @dalegriffiths3628
    @dalegriffiths36284 жыл бұрын

    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

  • @David-vz4yk
    @David-vz4yk4 жыл бұрын

    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

  • @CottidaeSEA
    @CottidaeSEA4 жыл бұрын

    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

  • @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.

  • @somerandomguy2892
    @somerandomguy28923 жыл бұрын

    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?

  • @manuelg8050
    @manuelg80504 жыл бұрын

    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

    3 жыл бұрын

    @@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.

  • @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; } }

  • @victorgomes9985
    @victorgomes99853 жыл бұрын

    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 :\

  • @TheJobKnockey
    @TheJobKnockey3 жыл бұрын

    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?

  • @Deathkid0990
    @Deathkid09904 жыл бұрын

    What do I do to Raycast2D

  • @kris007iron
    @kris007iron3 жыл бұрын

    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

  • @VladaPersonal
    @VladaPersonal3 жыл бұрын

    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.

  • @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.

  • @fedggg
    @fedggg4 жыл бұрын

    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

  • @animeoffighter8362
    @animeoffighter83624 жыл бұрын

    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.

  • @user-ir1hj5zb8z
    @user-ir1hj5zb8z4 жыл бұрын

    3 ways to melee attack ?

  • @vixexxfn2068
    @vixexxfn20683 жыл бұрын

    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

  • @paritoshmishra2572
    @paritoshmishra25724 жыл бұрын

    Can you share what code you have in CharacterAim_Base script.

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    I covered weapon aiming here kzread.info/dash/bejne/mKl7s6idmLa2l5c.html

  • @paritoshmishra2572

    @paritoshmishra2572

    4 жыл бұрын

    @@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

    4 жыл бұрын

    @@paritoshmishra2572 Sure, you can make a standard rifle that fires raycasts and a Rocket launcher that fires projectiles

  • @mr-spoon
    @mr-spoon4 жыл бұрын

    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

  • @gianp33

    @gianp33

    4 жыл бұрын

    ammunition fam ^^

  • @juicedup14
    @juicedup144 жыл бұрын

    how do I get the endpoint?

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    In my case it's the mouse click position

  • @juicedup14

    @juicedup14

    4 жыл бұрын

    @@CodeMonkeyUnity i meant where th bullet comes from

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    ​@@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 kzread.info/dash/bejne/mKl7s6idmLa2l5c.html In my case I also have an invisible point baked into my animations.

  • @juicedup14

    @juicedup14

    4 жыл бұрын

    @@CodeMonkeyUnity thanks

  • @aero7982
    @aero79823 жыл бұрын

    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.

  • @YTSHANKY
    @YTSHANKY3 жыл бұрын

    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 kzread.info/dash/bejne/dJqTl9OCpJytops.html The weapon aiming here kzread.info/dash/bejne/mKl7s6idmLa2l5c.html

  • @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

  • @bts-vz2wu
    @bts-vz2wu3 жыл бұрын

    Sir please tell how to make a our own game and program

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    Start off by learning the basics here kzread.info/dash/bejne/d2p1lrmvo6fLfKg.html And then here kzread.info/dash/bejne/e3qV27Oin6qdYaQ.html

  • @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.

  • @5252emre
    @5252emre3 жыл бұрын

    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

  • @MKHideOut
    @MKHideOut3 жыл бұрын

    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?

  • @DuyTran-ss4lu
    @DuyTran-ss4lu4 жыл бұрын

    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

  • @obesefrogman
    @obesefrogman2 жыл бұрын

    3:13

  • @gyorfiendre6867
    @gyorfiendre68673 жыл бұрын

    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 !

  • @Deathkid0990
    @Deathkid09904 жыл бұрын

    I Need a 3d raycast

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Then use Physics.Raycast(); instead of Physics2D

  • @Deathkid0990

    @Deathkid0990

    4 жыл бұрын

    @@CodeMonkeyUnity Thanks

  • @wonderflounium
    @wonderflounium3 жыл бұрын

    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 kzread.info/dash/bejne/Za6stsugmq3YYpc.html

  • @g5haco
    @g5haco4 жыл бұрын

    can you do 3D xD

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    4 жыл бұрын

    Most things I show in these videos are usable both in 2D and 3D kzread.info/dash/bejne/Za6stsugmq3YYpc.html

  • @g5haco

    @g5haco

    4 жыл бұрын

    @@CodeMonkeyUnity Oh sorry

  • @somedooby
    @somedooby2 жыл бұрын

    Video starts at 4:00

  • @wizzkw5921
    @wizzkw59214 жыл бұрын

    Can you replay of all the codes in this vid I don’t really have time to write and sorry if I bothered you

  • @s1pooky580
    @s1pooky5803 жыл бұрын

    dont work

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    What doesn't work?

  • @brahimbelmouhand9888
    @brahimbelmouhand98883 жыл бұрын

    using CodeMonkey; using CodeMonkey.Utils; ??

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    3 жыл бұрын

    Those are the namespaces for my utilities that you can download from the website

  • @motimimon1
    @motimimon13 жыл бұрын

    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
    @mateuszkowalczyk21492 жыл бұрын

    uninstall

  • @thomasyael1268
    @thomasyael12682 жыл бұрын

    how a can use the librery "using CodeMonkey.utils" thats librery unity doesn have

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    2 жыл бұрын

    That's my own utilities, you can download the source code from the website, or just write the code yourself

  • @gamingtech1934
    @gamingtech1934 Жыл бұрын

    Transform bulletTransform = Instantiate(Bullet, ToFirePoint , Quaternion.identity show to me Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Transform'

  • @CodeMonkeyUnity

    @CodeMonkeyUnity

    Жыл бұрын

    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

    Жыл бұрын

    @@CodeMonkeyUnity thanks it worked

  • @DAX_V
    @DAX_V3 жыл бұрын

    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 kzread.info/dash/bejne/Z52m2JVpXcW6eto.html