Тёмный

3 Ways to Shoot Projectiles in Unity! 

Code Monkey
Подписаться 543 тыс.
Просмотров 244 тыс.
50% 1

✅ Get the Project files and Utilities at unitycodemonke...
🌍 Get my Complete Courses! ✅ unitycodemonke...
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.uni...
❤️ 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 unitycodemonke...
📝 Get the Code Monkey Utilities at unitycodemonke...
#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: unitycodemonke...
Twitter: / unitycodemonkey
Facebook: / unitycodemonkey

Опубликовано:

 

7 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 224   
@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
@Xadness22
@Xadness22 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 3 года назад
good tutorial! gj
@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 RU-vid 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
@aquaarmour4924
@aquaarmour4924 4 года назад
Congrats on the unity sponsorship! great video
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Thanks! It's great to be officially recognized!
@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
@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!
@leagueoflags
@leagueoflags 4 года назад
Excellent tutorial, as always. I'm keeping my fingers crossed that this channel becomes your sustainable source of income!
@NeZversSounds
@NeZversSounds 4 года назад
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.
@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
@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; }
@jean-michel.houbre
@jean-michel.houbre 4 года назад
Hello, another smart and clear video for those who have to stay home. Thank you so much !
@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.
@CodesnippetBiz
@CodesnippetBiz 4 года назад
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!
@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
@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).
@hasnainfareed8555
@hasnainfareed8555 4 года назад
Wow,You are a real pro,Hard Work Pays
@perssontm1628
@perssontm1628 4 года назад
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.
@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
@matebliadze4425
@matebliadze4425 Год назад
YOU ARE THE BEST MAN
@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?
@wolffin4422
@wolffin4422 4 месяца назад
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.
@monsieuralexandergulbu3678
@monsieuralexandergulbu3678 4 года назад
Thanks for the tut. now i get 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
@hyjalonfire
@hyjalonfire 4 года назад
this video was awesome thanks
@armaankeshava8471
@armaankeshava8471 4 года назад
Nice job!keep up the good work
@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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fuGQFdhSPg4.html
@bruhmanbruhmanzz
@bruhmanbruhmanzz 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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-FbM4CkqtOuA.html
@kutanarcanakgul5533
@kutanarcanakgul5533 4 года назад
Hey man, Can you cover how can we make Pooling System for our games?
@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º
@physicschaosdev
@physicschaosdev 2 года назад
could you show how to shoot particle projectiles?
@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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-FbM4CkqtOuA.html
@TalhaRiaz197
@TalhaRiaz197 3 года назад
big fan of you
@Oxmond
@Oxmond 4 года назад
Coolio! 👍🤓
@kawakami_idv
@kawakami_idv 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.
@GARTZ09
@GARTZ09 3 года назад
if you dont mind, can you make a tutorial on creating goodlooking water 2d in unity.
@magnusm4
@magnusm4 Год назад
Is it possible to use Trigger on the particle system?
@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
@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 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.
@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
@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.
@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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-Bf_5qIt9Gr8.html
@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?
@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
@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.
@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
@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
@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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-h9oEhVqGptU.html ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-AXkaqW3E9OI.html
@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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-Eyx3EfqqfMw.html
@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.
@DerriStudios6969
@DerriStudios6969 4 года назад
Would you be able to use the first two shooting methods when you're programming enemy AI?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Sure, the bullet doesn't care if its fired by the player or an AI enemy
@davidcalderwood7041
@davidcalderwood7041 2 года назад
How can I apply rotation to the shootDir so the projectiles would be like a fixed shotgun pattern?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 года назад
shootDir = Quaternion.Euler(0, 45, 0) * shootDir;
@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.
@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?
@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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fuGQFdhSPg4.html
@MarkJrLuat
@MarkJrLuat 3 года назад
@@CodeMonkeyUnity is it the playeraimweapon script?
@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.
@yifengchen5274
@yifengchen5274 4 года назад
Is the collider in particle system any good for bullets?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Sure, you could use that as well
@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.
@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?
@YTSHANKY
@YTSHANKY 4 года назад
Please teach us making this sort of toturials form scartch... request from mee
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
This is showing how to shoot projectiles from scratch. For the character I covered it here ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-Bf_5qIt9Gr8.html The weapon aiming here ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fuGQFdhSPg4.html
@YTSHANKY
@YTSHANKY 4 года назад
@@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
@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 :)
@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.
@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?
@Deathkid0990
@Deathkid0990 4 года назад
What do I do to Raycast2D
@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
@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
@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 :\
@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; } }
@studenthtw-gamedesign5826
@studenthtw-gamedesign5826 4 года назад
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
@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
@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.
@pierceblk6838
@pierceblk6838 2 года назад
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
@user-ir1hj5zb8z
@user-ir1hj5zb8z 4 года назад
3 ways to melee attack ?
@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
@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
@bts-vz2wu
@bts-vz2wu 4 года назад
Sir please tell how to make a our own game and program
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Start off by learning the basics here ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-E6A4WvsDeLE.html And then here ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-IFayQioG71A.html
@VladaPersonal
@VladaPersonal 4 года назад
How do you get the shoot direction to cast the raycast?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
If you want to shoot towards the mouse then you do (mousePosition - playerPosition).normalized to get the direction vector.
@VladaPersonal
@VladaPersonal 4 года назад
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 4 года назад
@@VladaPersonal A single ray is extremely cheap, you only have to worry about performance if you're firing thousands every frame.
@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
@gianp33
@gianp33 4 года назад
ammunition fam ^^
@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?
@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
@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
@paritoshmishra2572
@paritoshmishra2572 4 года назад
Can you share what code you have in CharacterAim_Base script.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
I covered weapon aiming here ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fuGQFdhSPg4.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
@juicedup14
@juicedup14 4 года назад
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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fuGQFdhSPg4.html In my case I also have an invisible point baked into my animations.
@juicedup14
@juicedup14 4 года назад
@@CodeMonkeyUnity thanks
@gyorfiendre6867
@gyorfiendre6867 4 года назад
How can i use CodeMonkey.Utils ???
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Just download the package and import it into your project. It will add a folder with all the source files.
@gyorfiendre6867
@gyorfiendre6867 4 года назад
@@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 4 года назад
@@CodeMonkeyUnity i got the problem, sorry !
@Deathkid0990
@Deathkid0990 4 года назад
I Need a 3d raycast
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Then use Physics.Raycast(); instead of Physics2D
@Deathkid0990
@Deathkid0990 4 года назад
@@CodeMonkeyUnity Thanks
@somedooby
@somedooby 2 года назад
Video starts at 4:00
@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
@wonderflounium
@wonderflounium 4 года назад
youtube sucks, i search "projectiles in unity3d" and the first result is a unity2d tutorial
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
The logic is exactly the same, you just uses meshes instead of sprites ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-3zxTigjJr24.html
@wizzkw5921
@wizzkw5921 4 года назад
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
@s1pooky580 3 года назад
dont work
@CodeMonkeyUnity
@CodeMonkeyUnity 3 года назад
What doesn't work?
@brahimbelmouhand9888
@brahimbelmouhand9888 4 года назад
using CodeMonkey; using CodeMonkey.Utils; ??
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Those are the namespaces for my utilities that you can download from the website
@obesefrogman
@obesefrogman 2 года назад
3:13
@g5haco
@g5haco 4 года назад
can you do 3D xD
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
Most things I show in these videos are usable both in 2D and 3D ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-3zxTigjJr24.html
@g5haco
@g5haco 4 года назад
@@CodeMonkeyUnity Oh sorry
@mateuszkowalczyk2149
@mateuszkowalczyk2149 3 года назад
uninstall
@DizzyNoSkills
@DizzyNoSkills 4 года назад
get to to the freaking point man
@CodeMonkeyUnity
@CodeMonkeyUnity 4 года назад
What do you mean? What part do you feel I dragged on unnecessarily?
@DizzyNoSkills
@DizzyNoSkills 4 года назад
@@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
@thomasyael1268
@thomasyael1268 2 года назад
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_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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-5irv30-bTJw.html
Далее
What are Interfaces? (C# Basics)
13:54
Просмотров 209 тыс.
Little kitten 💓💜❤️🥰
00:17
Просмотров 18 тыс.
I Made A Difficult Game About Climbing
15:04
Просмотров 2,1 млн
How do non-euclidean games work? | Bitwise
14:19
Просмотров 2,4 млн
What are Events? (C# Basics)
15:05
Просмотров 393 тыс.
How I Made a 3D Platformer in 2D Game Engine
21:23
Просмотров 508 тыс.
How A Steam Bug Deleted Someone’s Entire PC
11:49
I Made the Same Game in 8 Engines
12:34
Просмотров 4,1 млн
3 Hours vs. 3 Years of Blender
17:44
Просмотров 5 млн
choosing a game engine is easy, actually
15:08
Просмотров 515 тыс.
What are Generics? (C# Basics)
13:48
Просмотров 148 тыс.
Little kitten 💓💜❤️🥰
00:17
Просмотров 18 тыс.