Aim at Mouse in Unity 2D (Shoot Weapon, Unity Tutorial for Beginners)

  Рет қаралды 189,120

Code Monkey

Code Monkey

Күн бұрын

Пікірлер: 472
@CodeMonkeyUnity
@CodeMonkeyUnity 5 жыл бұрын
Stay tuned for a complete Top-Down Shooter comign soon! 🎮 Play 7 Awesome Games (Action, Strategy, Management) and Help Support the Channel! ✅ Get the Game Bundle 67% off unitycodemonkey.com/gameBundle.php
@klarnorbert
@klarnorbert 4 жыл бұрын
Quick question: why not use raycasts? You can just skip the maths with that.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
@@klarnorbert I do use Raycasts to detect hits, not sure what you mean by "skip the maths", you need to first calculate the direction so you can use a raycast.
@klarnorbert
@klarnorbert 4 жыл бұрын
@@CodeMonkeyUnity I mean, using raycast to detect the mouse position in the game area, and then tranfsform.LookAt() that position.
@shalzy_
@shalzy_ 4 жыл бұрын
Bro can I just ctrlC+ctrlV the code without downloading the entire project
@Rayanthebest1
@Rayanthebest1 3 жыл бұрын
@@shalzy_ can you say where is the code
@MalikenGD
@MalikenGD 5 жыл бұрын
I wish you did more 3d work, but I gotta say, I absolutely love your commitment to the channel. It really shows.
@CodeMonkeyUnity
@CodeMonkeyUnity 5 жыл бұрын
Yeah I loved making the Hookshot so I'd definitely like to do more 3D stuff but there's still so much cool 2D stuff I haven't covered!
@kouni.i
@kouni.i 4 жыл бұрын
i started learning c# today and u are just explaining everything good and from nothing i still can understand something what are u doing. Good job dude!!! and thanks ofc
@broganking9830
@broganking9830 5 жыл бұрын
Man you're pumping out videos like there is no tomorrow!
@vijaychavan1625
@vijaychavan1625 3 жыл бұрын
its true... actually
@EggBlunt
@EggBlunt 3 жыл бұрын
I'm planning on remaking some Max Payne levels in a 2d side scrolling shooter, this helped out a lot thanks
@berkcan-upssslayer6521
@berkcan-upssslayer6521 4 жыл бұрын
The video is beautiful. I'm sure you appeal to many people from Turkey Turkish content we would love you to do.
@technoo4891
@technoo4891 4 жыл бұрын
Bro, your utils saved me with the get mouse position, I tried doing it "manually" and nothing was working correctly, thank you.
@charliegaming766
@charliegaming766 Жыл бұрын
if you are having a issue of not pointing your aim properly and aim away when you get closer to the player & you are using cinemachine victual camera to follow the player, just remove the camera controller script from the player if you are using one to follow the main camera behind the player. it will fix the issue. it fixed mine. hope this helps.
@nelyx5804
@nelyx5804 Жыл бұрын
Thx god i was searching for a long time to fix this, cinemachine are new to me so i was having difficulties to setup it, thx you man !
@charliegaming766
@charliegaming766 Жыл бұрын
@@nelyx5804 you are welcome 😊
@indraayy849
@indraayy849 5 жыл бұрын
You can just do: Vector3 aimDirection = mousePosition - transform.position aimTransform.right = aimDirection Less code and more performant
@CodeMonkeyUnity
@CodeMonkeyUnity 5 жыл бұрын
Hmm interesting, I've never seen anyone modify the transform.right directly, not sure if that works the same or bypasses anything. Knowing how to do math with angles is still helpful though, it's used to fire the weapon shell.
@teebs2721
@teebs2721 4 жыл бұрын
Where would you put this code?
@keni124
@keni124 5 жыл бұрын
I discovered this piece of code accidently but the code were much cleaner than to what I has coded
@sturmente
@sturmente 4 жыл бұрын
Thank you for the nice Tutorial. This is the first Tutorial what will work for my Game PS: Sorry for my Bad Englisch i am a 14 year old Kid from Germany :)
@ScribbleVicious
@ScribbleVicious 3 жыл бұрын
Great vid! I plan on trying this with a sword and sword trails for melee attacka
@edu2428
@edu2428 3 жыл бұрын
me too! Wish me luck lol
@hiddio
@hiddio 3 жыл бұрын
i’m making a guy who always has his hands in his pockets but can take out one of his arms to shoot laser beams PEW PEW PEW
@nilss.6367
@nilss.6367 2 жыл бұрын
I have a Problem, because in my console when i start it says Shoot_Flash can not be found in script Testing (line 20) can sb help me please, thanks
@BillyMan
@BillyMan 4 жыл бұрын
Super helpful man, love it!
@Matt-zx5jj
@Matt-zx5jj 4 жыл бұрын
Great video, one question though: At 13:30 you add the code to flip the gun depending on the angle, but I dont see how you are getting the whole player to point in that direction as surely that is handled in an animator elsewhere? Are you just adding a trigger to your main player animator to change on pointer angle?
@ShadowScorp99
@ShadowScorp99 3 жыл бұрын
Same, I'm still trying to figure out how he did that.
@caiquemoa
@caiquemoa 3 жыл бұрын
@@ShadowScorp99 any of you guys discovered how he did?
@LaserGadgets
@LaserGadgets 6 ай бұрын
After finishing with a D in the Jr Programmer path I am more demotivated than ever. 2D game but you are still writing vector3. No idea why. When I add this to my prototype my weapon is ordering around me. Instantiate(puke.prefab bla puke.prefab.rotation). And they say UE5 is even harder. Is it in chinese or something?
@CodeMonkeyUnity
@CodeMonkeyUnity 6 ай бұрын
Because at its core Unity is a 3D engine, you can use Vector2s if you want, they will just automatically be converted into Vector3. It sounds like you should focus on the absolute basics first, check out my free beginner courses kzbin.info/www/bejne/d56qhHh-bLaWesk kzbin.info/www/bejne/poPIg2mQbtd-Y9E
@LaserGadgets
@LaserGadgets 6 ай бұрын
@@CodeMonkeyUnity I did the Jr Programmer thing and starting from zero, I have to admit not all of it made it onto my bio-harddrive, but still. its like learning chinese and I can barely from sentences and even if I do it right, there comes another more complicated but "better" way to do it. Like no matter how much you learn, its never enough. Frustrating.
@CodeMonkeyUnity
@CodeMonkeyUnity 6 ай бұрын
Programming is a relatively complex skill so yes what you are describing is the perfectly natural learning process. It takes time to learn, that's normal. I've been programming for 25 years and I'm still learning new things
@LaserGadgets
@LaserGadgets 6 ай бұрын
@@CodeMonkeyUnity Yeah I guess it is. I am just asking myself how you actually learned all of this because all I am doing is watching people doing what I might need for my first attempt, and copy what they do....which is actually the way I did not wanna walk.
@ClaytonWasTaken
@ClaytonWasTaken 4 жыл бұрын
If anyone is also using a script that updates the Camera's position in LateUpdate, you will notice that the aiming stops working correctly the further you move away from your player's starting position. A simple fix that I found was moving HandleAiming(); into a LateUpdate instead of Update. You should keep HandleShooting(); in a regular Update as it uses Input.
@TheFunnyWizard_
@TheFunnyWizard_ 2 жыл бұрын
Why does this fix it?? Mine did not work when I did it
@MontyEditz
@MontyEditz 3 жыл бұрын
how do u change from LWRP to URP also another error about Light 2d how to solve these plz help
@random_precision_software
@random_precision_software 2 жыл бұрын
Ive got a grappling hook my player can use with the mouse ...SOUND NO Problemo ... BUT how do I use the right stick of the xbox controller as a mouse position in Unity old Input system? I have no problem getting th axis from the controller just working out the pos from the stick pos.. Dont Fancy doinf a tutorial ? hehe ?
@redsinc.9587
@redsinc.9587 11 ай бұрын
Hey I've been having trouble with the whole animating process(im new to unity). In the video you jumped to having the whole animation process done so I'm kind of stumped. I have already premade pixel animations and have the frames for the gun idle and gun shooting but not sure how to actually do what you did in the video. Some help would be appreciated or if you know of a video i can watch to help me back on track because a lot of the videos do it weird and don't do it how you had things set up. thanks!
@tobiasveith4838
@tobiasveith4838 4 ай бұрын
How can I make it so that I have a crosshair that rotates at a certain distance from the player to the mouse but does not rotate itself?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 ай бұрын
Since you know the direction vector from the player towards the mouse, you can just manually position it through code, instead of making it a child game object visual crosshairTransform.position = playerPosition + dirToMouse * distanceOffset;
@lukastomasek8038
@lukastomasek8038 5 жыл бұрын
I was looking for this topic , thanks for creating this tutorial !
@syndcake6807
@syndcake6807 4 жыл бұрын
Hi, i have a problem with the code, i copied your code exactly but, i keep getting an error message "NullReferenceException: Object reference not set to an instance of an object PlayerAimWeapon.Update () (at Assets/scripts/PlayerAimWeapon.cs:21)"
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
You have some variable set to null, check that line to see what it is. You probably forgot to drag a reference in the editor.
@syndcake6807
@syndcake6807 4 жыл бұрын
@@CodeMonkeyUnity That line is aimTransform.eulerAngles = new Vector3(0f, 0f, angle); and there aren't any references to drag
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
@@syndcake6807 In that line the only thing that can be null is aimTransform That should be set using Find(); so check the name, it has to be exact, it's case sensitive
@victoonix2802
@victoonix2802 2 жыл бұрын
@@CodeMonkeyUnity I checked but it still doesn't work. It's set to "Aim", which is absolutely right
@berogames3256
@berogames3256 4 жыл бұрын
Many thanks for your effort ,you are really make me happy by seeing your vedio
@boogiewg5141
@boogiewg5141 2 жыл бұрын
When I use this, the "gun" is shaking/vibrating/jittering when the player is moving in any direction. I have tried changed execution orders and many combination of update, lateupdate and fixed update, but to no avail.
@alrexomandam1774
@alrexomandam1774 4 жыл бұрын
May I know how do you make the camera follow the cursor a little bit when you move the cursor into a specific place?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
The camera follows a position that is shifted towards the mouse position by half the distance cameraFollowPosition = playerPosition + mouseDirection * (mouseDistance * .5f);
@alrexomandam1774
@alrexomandam1774 4 жыл бұрын
@@CodeMonkeyUnity is there any video about that so that I can follow on along. I don't know where those codes came from. Sorry still a newbie
@alrexomandam1774
@alrexomandam1774 4 жыл бұрын
also how do make the character face the cursor, i followed everything on the video but mine is not working
@JentlerYT
@JentlerYT 4 жыл бұрын
ok, sorry for all this, I downloaded the Utils, but there's still a little problem... the weapon doesn't follow the mouse correctly... for example, when my mouse is on the top of the screen, the weapon is facing right...
@JentlerYT
@JentlerYT 4 жыл бұрын
in conclussion, the controls are inverted.
@xCratuss
@xCratuss 4 жыл бұрын
@@JentlerYT seems like you have done a mistake at one part of the video. check your code. for me it worked today.
@JentlerYT
@JentlerYT 4 жыл бұрын
I have checked the code so many times! What Unity version do you use?
@xCratuss
@xCratuss 4 жыл бұрын
@@JentlerYT the newest one.
@tiubert6140
@tiubert6140 8 ай бұрын
In general, the tutorial is cool, but... I would like to find the code that makes the camera move with the cursor. Perhaps I missed some part of the video or video from the playlist
@tiubert6140
@tiubert6140 8 ай бұрын
This is my work (script on camera, in Update) transform.position = (player.position + Camera.main.ScreenToWorldPoint(Input.mousePosition)) / 2
@CodeMonkeyUnity
@CodeMonkeyUnity 8 ай бұрын
Yup that's exactly it, just get the mouse world position and position the camera wherever you want, maybe on the mouse position itself, maybe always on the player, or in the halfway point between the player and the mouse
@dinukachathurangashow8571
@dinukachathurangashow8571 Жыл бұрын
Dear code monkey: i did everything but gun is not pointing exactly where the mouse is at(little down) when I drag if farther away from the player. when I get closer it rotates all the way to the back, not pointing at the mouse position correctly. additionally i have used the Cinemachine noise camera holding effect. how can i fix this? i wish if u could reply the fixing code as well if possible.
@motttti
@motttti 3 жыл бұрын
I can't get the gun to flip when it goes past 90 degrees, anything wrong with this? private void Update() { Vector3 mousePosition = UtilsClass.GetMouseWorldPosition(); Vector3 aimDirection = (mousePosition - transform.position).normalized; float angle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg; AimPivot.eulerAngles = new Vector3(0, 0, angle); Vector3 aimlocalScale = Vector3.one; if (angle > 90 || angle < -90) ; { aimlocalScale.y = -1f; } else { aimlocalScale.y = +1f; } AimPivot.localScale = aimlocalScale; } }
@bemtheman1100
@bemtheman1100 2 ай бұрын
this may be a bad question. I am just wondering if it is at all possible to have something like this switch between mouse and the right stick of a gamepad. Using the mouse the gun follows the cursor but with game bad the gun will go in the direction of the right stick. Is it possible to do something along the lines of moving between these two control schemes?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 ай бұрын
Sure, you can listen to either mouse input or gamepad input and set the latest one as the active one. I did something like that in my Virtual Cursor video kzbin.info/www/bejne/oGO7qq2JdqlnjLc
@bemtheman1100
@bemtheman1100 2 ай бұрын
@@CodeMonkeyUnity does the same aiming logic work for both mouse and right stick?
@speedrob
@speedrob 5 жыл бұрын
Hehe for once I'm ahead of the game here with this one, but still very cool and sought after.
@JentlerYT
@JentlerYT 4 жыл бұрын
Damn it I wanted a platformer Aim at mouse Tutorial...
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
It works exactly the same, apply gravity to the character and all of a sudden you have a platformer.
@JentlerYT
@JentlerYT 4 жыл бұрын
Code Monkey oh thanks!
@dianpratama9507
@dianpratama9507 3 жыл бұрын
Thks for tutorial bro!!
@Makaplakka
@Makaplakka Жыл бұрын
how do you make your player change directions without the pistol sprite also moving in that direction?
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
Depends on how you are handling the player changing directions, sounds like maybe you are inverting the localScale.x? If so one solution is to not make the weapon a child of the player, make it a separate object and just make it follow the player position
@caiquemoa
@caiquemoa 3 жыл бұрын
the part that i was most interested you just skiped as "quick polishing" did you teach it in other video or are you saving for your course? if yes which one
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
What part? The Screenshake? That depends on how you set up the camera, in this case I had a normal camera so I just move it randomly for a few frames, if you have Cinemachine you add some noise. The shoot flash? It just spawns a sprite for the flash and destroys it after 1 or 2 frames. The bullet trace? I covered it here kzbin.info/www/bejne/oHXMcq2uoL6tpqs And the bullet particles I covered that here kzbin.info/www/bejne/iZzOqaqpjdx4nsU
@caiquemoa
@caiquemoa 3 жыл бұрын
@@CodeMonkeyUnity the 13:30 part the sprite turn toward the mouse, i'm trying to make this to but mine just turn when he is in the center of the map, if the player is far from the center and the mouse is >> because the mouse is >> from the center kkk
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
@@caiquemoa Sounds like you're using the direction from the center of the screen to test where the player should look when instead you should calculate the direction from the player to the mouse position. Do (mousePosition - playerPosition)
@caiquemoa
@caiquemoa 3 жыл бұрын
@@CodeMonkeyUnity Ty was exactly that
@jdaggrrr575
@jdaggrrr575 3 жыл бұрын
Could we get a tutorial on how to make this burst fire? also how would i make the weapon flip instead of being upside down when i point it left? im very new to coding (:
@twobits7310
@twobits7310 4 жыл бұрын
how to rotate character's weapon in moving direction, Shooting in direction of the character movement. I don't want to use mouse.
@kuo-kun7915
@kuo-kun7915 3 жыл бұрын
Can I do the katana zero mouse attack thingy?
@РичардТриальд
@РичардТриальд 3 жыл бұрын
Strangely, but when i swapped x and y in math formule, for me all was completed Also, how do you connected muzzle flash to animation, cause animator set in pistol, and in script i didn't found any stroke of code that connecting that
@Bruzen
@Bruzen 4 жыл бұрын
Seems complicated you do a lot of fast motion I can’t understand
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
What couldn't you understand? You can pause the video to follow along at your speed.
@Bruzen
@Bruzen 4 жыл бұрын
Code Monkey I’ll try.
@chossy5098
@chossy5098 4 жыл бұрын
😆CodeMonkey the speed runner of programming. I don't like it either it puts me off using anything he puts out play at 0.5 pause go back ect.. but as he said you can pause the video. I normally get 1/4 in and think na & stop watch shame as it's great content.
@Bruzen
@Bruzen 4 жыл бұрын
Chossy yep
@JentlerYT
@JentlerYT 4 жыл бұрын
Code Monkey I need help the pistol doesn’t follow the player correctly. When the mouse is on top of the screen the pistol is facing right and when the mouse is at the bottom of the screen the pistol is facing left!
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Make sure the default orientation of your aim game object is pointing to the right. Or just add 90º through code.
@JentlerYT
@JentlerYT 4 жыл бұрын
@@CodeMonkeyUnity Pls how do I add 90 degrees through code? (I am a complete beginner as you can see)
@hellodarkness4572
@hellodarkness4572 2 жыл бұрын
I dont know why but my animation doesnt play even when i have it all hooked up and the trigger is working, and the transitions work as well. please help.
@pamalott5
@pamalott5 3 жыл бұрын
Do you make your 2D Art yourself and which Programm do you use?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
I draw in Photoshop
@pamalott5
@pamalott5 3 жыл бұрын
@@CodeMonkeyUnity ok thx 👍
@biimyflipps
@biimyflipps 3 жыл бұрын
if i have a working "aim" system can i skip the part or do i need this one for that the shooting shal work
@joaquincastillo3912
@joaquincastillo3912 4 жыл бұрын
Good video :D This works in a 2D side looking shooter game?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Sure, it just points towards the mouse so you could use it in a SideScroller/Platformer
@almaalma3464
@almaalma3464 2 жыл бұрын
Player follow mouse: For the character I just calculate the Vector towards the mouse, convert that into a Euler Angle and split that into 8 then play the specific animation for that direction.
@Ventinky
@Ventinky 4 жыл бұрын
thanks code monkey, i subscribed, you helped my game :)
@victoonix2802
@victoonix2802 2 жыл бұрын
Hey Code Monkey, great tutorial! This helped me a lot. Just wondering how you would make an automatic gun work while still triggering the event. Edit: Also, while you're at it, how did you make the camera follow the mouse slightly like that?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Make a float timer and call the shoot function every few ms You can get the mouse position unitycodemonkey.com/video.php?v=0jTPKz3ga4w Then calculate the direction from the player towards the mouse And make the camera look at a point in between the player and the mouse
@victoonix2802
@victoonix2802 2 жыл бұрын
@@CodeMonkeyUnity Thanks a lot, you're the best!
@simonradberg
@simonradberg 3 жыл бұрын
My muzzleflash is not at the guntip its super long away from the gun how do i fix this?
@MarkJrLuat
@MarkJrLuat 3 жыл бұрын
Hey, sorry I keep asking so many questions but I followed ur projectile tutorial but when I did the first way of shooting projectile the bullet just spawns at the bottom right of my character.
@WAMBHSE
@WAMBHSE 5 жыл бұрын
Could you please do a video on how to do this for a twin stick controller set up and also include how to have a cross hairs move with the direction of the controller input, Thank you very much! another great video.
@CodeMonkeyUnity
@CodeMonkeyUnity 5 жыл бұрын
For that you really just need to replace the mouse position with a vector that you modify based on your stick input, everything else is the same, your character will point towards that vector position.
@Drizxander
@Drizxander 4 жыл бұрын
I am having a problem. At 8:30 the sprite is showing at some distance ahead from the gun. It doesn't matter where the MuzzleFlash gameobject is placed in scene. It always shows at that same position. Please help me with this issue.
@raidoksgames3510
@raidoksgames3510 4 жыл бұрын
I have same problème you fixed that?
@Drizxander
@Drizxander 4 жыл бұрын
@@raidoksgames3510 No I couldn't fix it
@curialbellic
@curialbellic 2 жыл бұрын
How do you make the gun stand behind the character when aiming upwards?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Depends on how your character/animations are set up, you need to play with SortingOrder or move the mesh on the Z
@cbaker1514
@cbaker1514 3 жыл бұрын
DId i miss something? It says for beginners but when creating the project im not sure whether to chose 3d or 2d... also theres already a background behind the character. He doesnt mention how to get that background
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
The topic of the video is 2D aiming so that's what it covers, if you want to learn the general basics of Unity watch this one kzbin.info/www/bejne/e2ekZYqsqKmYgqc
@StupendousStudios-bg4yy
@StupendousStudios-bg4yy Жыл бұрын
Hello -- I'm stumped on a null reference I'm getting for the event. I started with the 2d character controller tutorial w/ dodge roll & dash, then this aiming tutorial, and now trying to add the shooting in the 3 ways to shoot tutorial - and the OnShoot event is giving me an error on first click. 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; } }
@spartanranger
@spartanranger Жыл бұрын
Man did you fina a solution? I have the same exact problem and I'm losing hair helb
@CrCRccccc
@CrCRccccc 3 жыл бұрын
i have a problem with an animator, so when i add an animator component my pistol stop looking at mouse, what should i do?
@CorpSlay
@CorpSlay 5 жыл бұрын
i have 1 question, i downloaded the codemoney utility. unity put this utility under the assets.. is that the exact folder? or i have to move to another section for having all setup and ready for this tutorial and other you made?
@CodeMonkeyUnity
@CodeMonkeyUnity 5 жыл бұрын
You just need to double click the .unitypackage file and it gets added to your assets folder. Now open up a new script and you should be able to add "using CodeMonkey.Utils" and browse all the utilities source code.
@CorpSlay
@CorpSlay 5 жыл бұрын
Ok thanks a lot. Love your videos man, they are very accurate. Keep up the good work
@SleepingDaemon
@SleepingDaemon 4 жыл бұрын
Hello, CodeMonkey, how would I go about adding other projectile weapons with this setup?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
I covered several methods of handling projectiles here kzbin.info/www/bejne/hJzIZn2Bhc6Eitk
@tobi_jazz
@tobi_jazz 2 жыл бұрын
i copied your code excactly, but i got the same error message(NullReferenceException: Object reference not set to an instance of an object) over and over again. Why am I getting these but not you
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Use Debug.Log to find what is null unitycodemonkey.com/video.php?v=5irv30-bTJw
@viktorvanchov3093
@viktorvanchov3093 5 жыл бұрын
Hey, can you make a 2d building system? I tried finding other turtorials but they were either outdated or a turtorial about 3D building. I started a project where bulding is esential and it would really help if you made a turtorial about it.
@CodeMonkeyUnity
@CodeMonkeyUnity 5 жыл бұрын
Yeah city builder tutorials is something I definitely want to cover but not sure when.
@it8674
@it8674 2 жыл бұрын
Hello! Your code is working well on my project except for a strange issue: when I rotate the weapon(pixel) it will stretch and make the weapon distort. Are there ways to solve this problem?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Stretch? It should be rotating on the correct axis, should not "stretch" or deform in any way, maybe you're rotating on the wrong axis? Or you're just using pixel art and talking about pixels being off, if you use no anti aliasing then yes some angles will look off in a perfect pixel art game. For that the only solution is to not use this system and draw some specific rotation sprites and swap sprites instead of rotating the game object.
@it8674
@it8674 2 жыл бұрын
​@@CodeMonkeyUnity Hi! I just found it out, the object which has the mouse aim script in my project is not a square, hence unity will distort the weapon. Your code is working well, I just forgot that the result of drawing a circle around a rectangle is of course an oval!😂
@alexiosv7954
@alexiosv7954 3 жыл бұрын
I am having an issue activating my CodeMonkey account.... the confirmation link is not working....I need to download the project files of this project so i can learn a few things..
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
You didn't receive it? Check your spam folder
@alexiosv7954
@alexiosv7954 3 жыл бұрын
@@CodeMonkeyUnity Receiving it but the link is not working says too long to respond and doesn't activate anything
@Daniel-do2mh
@Daniel-do2mh 4 жыл бұрын
Hmm, do you know how could I translate it for mobile? (android) Like, with one finger you move the weapon and the other one you aim/shoot. (You control the weapons, not a character)
@curialbellic
@curialbellic 2 жыл бұрын
Do you have a tutorial on how to make the camera move smoothly to where you point the cursor?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
I made a camera system here unitycodemonkey.com/video.php?v=pJQndtJ2rk0 And mouse position here unitycodemonkey.com/video.php?v=0jTPKz3ga4w Just play with the smoothing to get the speed you want
@reubenfry7382
@reubenfry7382 3 жыл бұрын
Error : UtilsClass does not exist in the current context Help EDIT: fixed it I didn't download the utils package
@jeremiahbennett3004
@jeremiahbennett3004 3 жыл бұрын
Wondering here, is there a way to add knockback to these projectiles? I want to add a way to use movement with knockback from a projectile, any good ways I can do that?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
It depends on how you're controlling your characters, could be with rigidbody.AddForce or just moving the transform.position
@semimode
@semimode 4 жыл бұрын
Hey, Can you make a video about how to make that kind of character that you use in almost every video?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
I covered how my animation system works here: kzbin.info/www/bejne/Z2LGaqWNh9SngJo Its all based on dynamically modifying meshes in runtime
@semimode
@semimode 4 жыл бұрын
@@CodeMonkeyUnity I watched it and honestly didn't understand anything😂
@semimode
@semimode 4 жыл бұрын
@@CodeMonkeyUnity And im not really professional at making games. But i wanted to make that kind of animated character into one of mine training game.
@tadeopuga9888
@tadeopuga9888 Жыл бұрын
Hi, I followed your tutorial step by step, but when I ran the project it just hit me with a lot of NullReferenceExceptions. How can I fix that?
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
Use Debug.Log to find what is null unitycodemonkey.com/video.php?v=5irv30-bTJw
@SupertigerDev
@SupertigerDev 2 жыл бұрын
How can I find free to use player textures that are holding the gun that will work like this?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
There's tons of free sprites on the Unity Asset store or OpenGameArt
@kum914
@kum914 3 жыл бұрын
for me when i have my mouse pointer on the side the gun points upwards and when the mouse pointer is pointing upwards the gun is pointing sideways why is that?
@Tiparium_NMF
@Tiparium_NMF 3 жыл бұрын
How would you incorporate twin stick shooter style controls into this? This behavior is perfect for KBM, but I want KBM and controller to behave effectively the same.
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
You would just make a virtual cursor for the mouse position that you would move with a joystick
@frostbeard9542
@frostbeard9542 4 жыл бұрын
Every minute of this tutorial and ever other tutorial takes averagely an hour to research and understand.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
You just described the normal learning process. This is not a race so dont worry about how much time it takes you to learn something, just focus on actually learning it.
@frostbeard9542
@frostbeard9542 4 жыл бұрын
@@CodeMonkeyUnity Thanks for the advice, I just started game development and learned how long it takes to fully understand a concept. I also didn't mean anything critical in my comment of your tutorials. Infact you've helped me learn a lot about how to code and use Unity's software in your them.
@joecraft9098
@joecraft9098 3 жыл бұрын
Um ik this is a year later, but can u plz tell me y GetMouseWorldPosition isn't working with Vector3 in unity 2019.4?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
How is it not working? The logic is the same on every Unity version. Are you working on a 3D game? If so you need a different method to get the mouse world position
@baldski2656
@baldski2656 3 жыл бұрын
Yo, is your website fixed yet? Can't make an account to download the project files...
@lspremul
@lspremul 4 жыл бұрын
Hi Code Monkey, I was curious how you would apply the rotation of the character over a period of time? Would something like this work? aimTransform.eulerAngles = new Vector3(0, 0, angle) * rotationSpeed * Time.deltaTime?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Sure, that would rotate it continuously. If you want to rotate smoothly and stop you can look into Mathf.Lerp();
@lspremul
@lspremul 4 жыл бұрын
@@CodeMonkeyUnity Oh ok cool thanks for the tip!
@mikoajtworzy3157
@mikoajtworzy3157 2 жыл бұрын
help me i have error Assets\Scripts\playeraimwepon.cs(18,32): error CS0103: The name 'UtilsClass' does not exist in the current context
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Do you have the utils in the project? That's not a built in class, it's my own utilities which you can download from the website, or you can just write your own
@asdf-nn7mb
@asdf-nn7mb 4 жыл бұрын
how to flip the player in the direction of the mouse?
@masonbezzer5940
@masonbezzer5940 3 жыл бұрын
How are you meant to do the animation? Is there another video i can watch which explains it?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
It's a game object so you animate just like you would any other game object
@TheCeglaaa
@TheCeglaaa 4 жыл бұрын
Hey, I've been trying to make this work but my object just doesn't rotate at all. When I switch the code to Vector3 mousePosition = Camera.main.ViewportToScreenPoint(Input.mousePosition); it works but in a strange way, where moving the mouse rotates the character but it doesn't point at the mouse position. My full code is: Vector3 mousePosition = Camera.main.ViewportToScreenPoint(Input.mousePosition); Vector3 dir = (mousePosition - transform.position).normalized; dir.z = 0; float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; transform.eulerAngles = new Vector3(0, 0, angle);
@TheCeglaaa
@TheCeglaaa 4 жыл бұрын
Ok, I managed to handle it. If anyone has a problem, here's what was wrong - you need get the position from the camera's point of view on the player as well (dunno why tho). This is how you should calculate dir for it to work Vector3 dir = (mousePosition - Camera.main.WorldToViewportPoint(transform.position)).normalized;
@Mikael._
@Mikael._ 4 жыл бұрын
Thanks for the awesome content. I'll make a small shooter, nothing more than some squares shooting at each other to begin... I have a simple question: In my C# scripts i can't make one class "find" other classes or scripts. Let's say i am editing the script "MainScript", and then i add a line like this "SecondScript.Functionxxxxx", when you do that, your code has the autofills for the functions or events. Like in this tutorial, the "subscribe to the event" part, mine wont be highlighted in blue and wont have those autofills. That happens with the "EventHandler", "Vector3", "Input", etc. The thing is that they work fine, but it seems my Visual Studio don't know them. (I instaled it after Unity from MS website and did the "Create Unity games" instalation). Sorry for the ̶s̶i̶m̶p̶l̶e̶ big question. :P
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Does your visual studio recognize Unity classes? Like Debug and Vector3? Try manually installing the Unity Tools for VS docs.microsoft.com/en-us/visualstudio/cross-platform/visual-studio-tools-for-unity?view=vs-2019
@Mikael._
@Mikael._ 4 жыл бұрын
​@@CodeMonkeyUnity Thanks for the help, it was not recognizing "Vector3, Debug, [SerializeField], other classes (project ones or even UtilsClass.xxxx), Vector2, etc..." It recognizes only core C#, like the functions, Int, bool, float, etc. I looked into the link you sent and it was the instalation i did before. (i instaled Unity w/ VS, then instaled it from MS when i started snake tutorial), so if my instalation was right (into work loads it was Unity Development)... there was something in between VS and unity I saw in a forum answer the guy said to enable VS Comunity in Unity preferences as the default C# tool, mine was auto. It works now, just select VS Comunity in Edit>Preferences>External tools And check the "Editor Attaching" box. Then open your scripts from your Scripts folder in unity and now VS recognize everything. Save them all into a single project and all should work fine. I'll leave it here in case anyone have the same problem...
@robotplays346
@robotplays346 4 жыл бұрын
Mikael yes, I have that problem, are you on PC? If you are, that is the PC version, not a bug
@N1thium
@N1thium 5 жыл бұрын
Hi! Nice tutorial mate! Can you make an special about mobile controllers? Thanks!
@CodeMonkeyUnity
@CodeMonkeyUnity 5 жыл бұрын
Like 3rd party gamepads? Those are very difficult since they're all different, you're probably better off using an asset that already has a lot of them implemented like Rewired.
@N1thium
@N1thium 5 жыл бұрын
@@CodeMonkeyUnity Oh no no i mean the ones we make with scripts and UI! Hehehe
@ayedabboushi7221
@ayedabboushi7221 4 жыл бұрын
Can we use some of the materials such as weapons in our games for free?
@coutnico-f9265
@coutnico-f9265 3 жыл бұрын
This content is amazing but first i need to learn more basic things. its a little too much for me today. maybe not tomorrow :)
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
If you're new to Unity watch this video kzbin.info/www/bejne/e2ekZYqsqKmYgqc
@coutnico-f9265
@coutnico-f9265 3 жыл бұрын
@@CodeMonkeyUnity okay,will do now. Hey did you notice that the code monkey app in steam is working bad? or maybe i need to reinstall it. I cant use the Search function to find videos on it now
@coutnico-f9265
@coutnico-f9265 3 жыл бұрын
i think now is a good moment to tell you: your work on this channel is amazing and we (as any starting game dev) love you for this
@hawtrawd69
@hawtrawd69 Жыл бұрын
hey man, i have a question, it gives me an "Object reference not set to an instance of an object" error in unity, at the line with aimTransform.eulerAngles = new Vector3(0, 0, angle); . Do you happen to know why?
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
That means you have a null reference, meaning a reference that hasn't been assigned to anything In that line the only thing that can be null is aimTransform, so you probably didn't name the child exactly teh same name as you used in Find(); Whenever you have that error always use Debug.Log to find out what is null unitycodemonkey.com/video.php?v=5irv30-bTJw
@sanspseudofix8814
@sanspseudofix8814 6 ай бұрын
Hello thanks for this tuto But i want to know how to do that this netcode I tried but the weapon dont follow the player
@CodeMonkeyUnity
@CodeMonkeyUnity 5 ай бұрын
You just need to synchronize a vector3 for where each player is aiming
@roglSimpson
@roglSimpson 4 жыл бұрын
Have you had any issues with weapon rotation stuttering or being jerky as the mouse pointer gets closer to the character (it works just fine when mouse pointer is further away)? If so, what was the secret sauce to resolve it? Thanks in advance!
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
One way you can solve it is smooth out the rotation, perhaps with a maximum speed. Although that would also make your game less responsive so it really depends on your design
@roglSimpson
@roglSimpson 4 жыл бұрын
Thanks for the reply! In the end, it turned out I was using the wrong pivot point. I tried calculating the rotation using the weapon's fire point game object, instead of using the arm shoulder as a pivot point and offsetting by Y coordinate of the fire point.
@barkmober
@barkmober 2 жыл бұрын
@@CodeMonkeyUnity Can you continue spiderman
@namangupta4033
@namangupta4033 4 жыл бұрын
Hey, I don't know for some reason there's a time lag between clicking the mouse button and the playing of the animation. Very small, like a 0.3 sec time lag, but it's there. What should I do about it ?
@tarkozkan6439
@tarkozkan6439 4 жыл бұрын
you can change sensivity for Inputs in project settings it should do the trick
@sundarakrishnann8242
@sundarakrishnann8242 4 жыл бұрын
I guess you have to uncheck has exit time in animation transition...
@Cenji
@Cenji 3 жыл бұрын
How do I import the Weapon Aim file into unity?
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
It's a .unitypackage so just drag and drop on your unity project window
@lordaarush955
@lordaarush955 2 жыл бұрын
Hey, is there any way to hide the mouse pointer AND have the rotation work simultaneously?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Sure, changing the Cursor.visible does not impact Input.mousePosition
@lordaarush955
@lordaarush955 2 жыл бұрын
@@CodeMonkeyUnity thanks!
@goldenx-dragon2327
@goldenx-dragon2327 2 жыл бұрын
CodeMonkey i got a problem with this script. It says NullReferenceException: Object reference not set to an instance of an object PlayerAimWeapon.Update (). Could you help me?
@CodeMonkeyUnity
@CodeMonkeyUnity 2 жыл бұрын
Use Debug.Log to find what is null unitycodemonkey.com/video.php?v=5irv30-bTJw
@mr_kwkd
@mr_kwkd 4 жыл бұрын
why does mine stretch and stuff? Its exactly the same code in the video, and it does point, but it stretches and warps. Does anyone have a fix?
@mr_kwkd
@mr_kwkd 4 жыл бұрын
And also im getting the error (The script is called Pivot): UnassignedReferenceException: The variable aimTransform of Pivot has not been assigned. You probably need to assign the aimTransform variable of the Pivot script in the inspector. UnityEngine.Transform.set_rotation (UnityEngine.Quaternion value) (at :0) UnityEngine.Transform.set_eulerAngles (UnityEngine.Vector3 value) (at :0) Pivot.Update () (at Assets/Scripts/Pivot.cs:15) Im not doing any of the animation/gun stuff just the pointing at mouse
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Check the scale of the parent of the object you're rotating, it should be 1,1,1
@xiaoyou9412
@xiaoyou9412 4 жыл бұрын
Mr.Code Monkey, I am following you video "Aim at mouse in Unity" doing game and here is a problem:when I finished joining the gunflash into the sprite Aim, the animation did but the flash animation happens far away from the gun,can you tell me where is wrong?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
When you move an object in an animation it moves the Local Position of that object and not the Global Position Make sure your gun has a parent object and move the parent while leaving the gun always at its origin local position
@xiaoyou9412
@xiaoyou9412 4 жыл бұрын
@@CodeMonkeyUnity Thanks,I have solve my problem
@byDiAbLo21
@byDiAbLo21 4 жыл бұрын
Hi, I've got a problem, all seems good but when my mouse is close/over the aim transform my gun starts flickering how could I solve this?
@anonymoussloth6687
@anonymoussloth6687 4 жыл бұрын
Add a gun rotation dead zone which means set a specific threshold for the mousePosition - player's position so that the gun doesn't rotate when the mouse is really close to the player.
@julius6521
@julius6521 4 жыл бұрын
When I use your script or countless others i that I have tried, the gun just rotates to some direction (random depending on position) and then stays like that. When I move the mouse it only rotates insanely little. I'm in the Unity 2019 version and I have no idea what I'm doing wrong. Help?
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Verify that you're grabbing the Mouse World Position and doing all the math correctly. Add a bunch of Debug.Log in various places kzbin.info/www/bejne/a5rVp2ZmYseHgNk
@AustraliaM69
@AustraliaM69 7 ай бұрын
how did u get it to actually rotate around the player? it rotates in spot at 5:25 but rotates all around the player after you add hands? what am i missing
@CodeMonkeyUnity
@CodeMonkeyUnity 7 ай бұрын
It always rotates around the pivot, so you move the child objects to some offset which will cause it to rotate around the pivot unitycodemonkey.com/video.php?v=NsUJDqEY8tE unitycodemonkey.com/video.php?v=qa5WBatZ830
@yahyashafqat7352
@yahyashafqat7352 4 жыл бұрын
yo dude iam not able to add player to playeraimweapon for some reason. i realy followed every move but still i am not able to add it
@xeb0lax
@xeb0lax 4 жыл бұрын
When i click left mouse click the animaton not happens or i cannot see the muzzleflash
@raidoksgames3510
@raidoksgames3510 4 жыл бұрын
You fixed ?
@hengsopheata9147
@hengsopheata9147 Жыл бұрын
Hi CodeMonkey I having problems with the aiming, I did everything in the tutorial and it keep saying "NullReferenceException: Object reference not set to an instance of an object" in the console on the 21nd line "aimTransform.eulerAngles = new Vector3(0, 0, angle);" Please help.
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
In that line the only thing that could be null is the aimTransform, use Debug.Log to verify unitycodemonkey.com/video.php?v=5irv30-bTJw Remember that Find(); is case sensitive, the name must match the child name exactly
@robotplays346
@robotplays346 4 жыл бұрын
Hi, how would I make it so you can only aim a little bit
I Paid Fiverr Game Developers to Make the Same Game
10:25
BadGameDev
Рет қаралды 735 М.
Don't WASTE 5 Years!
11:35
Code Monkey
Рет қаралды 63 М.
1, 2, 3, 4, 5, 6, 7, 8, 9 🙈⚽️
00:46
Celine Dept
Рет қаралды 33 МЛН
the balloon deflated while it was flying #tiktok
00:19
Анастасия Тарасова
Рет қаралды 35 МЛН
这是自救的好办法 #路飞#海贼王
00:43
路飞与唐舞桐
Рет қаралды 102 МЛН
СОБАКА ВЕРНУЛА ТАБАЛАПКИ😱#shorts
00:25
INNA SERG
Рет қаралды 1,7 МЛН
Unity 2D Aim and Shoot at mouse position Tutorial
14:39
MoreBBlakeyyy
Рет қаралды 83 М.
3 Ways to Shoot Projectiles in Unity!
23:07
Code Monkey
Рет қаралды 245 М.
How to Aim a weapon at Mouse in Unity 2D
12:40
Sunny Valley Studio
Рет қаралды 38 М.
Character Controller in Unity 2D! (Move, Dodge, Dash)
23:41
Code Monkey
Рет қаралды 119 М.
Why Solo Developers Should Use Unreal
9:51
Thomas Brush
Рет қаралды 415 М.
60 DAYS to ACHIEVE your GOALS!
5:39
Code Monkey
Рет қаралды 6 М.
When Optimisations Work, But for the Wrong Reasons
22:19
SimonDev
Рет қаралды 1 МЛН
Optimizing my Game so it Runs on a Potato
19:02
Blargis
Рет қаралды 644 М.
Ability Bar in Unity (Swap Weapons/Items)
29:07
Code Monkey
Рет қаралды 32 М.
HOW TO MAKE 2D GAME ANIMATIONS IN UNITY - BEGINNER TUTORIAL
14:58
Blackthornprod
Рет қаралды 600 М.
1, 2, 3, 4, 5, 6, 7, 8, 9 🙈⚽️
00:46
Celine Dept
Рет қаралды 33 МЛН