- Home /
Issue with mouse position script
I am currently using the user's mouse position to fire bullets in my 2D top down game, but it is not working as intended. Here is my script to determine the user's mouse position and apply the vector to the bullet:
void Start () {
cam = Camera.main;
Vector3 mouse = cam.ScreenToWorldPoint(Input.mousePosition);
mouse.z = 0;
Vector2 moveVelocity = mouse.normalized * bulletSpeed;
rb.AddForce(moveVelocity);
}
The script works exactly as intended when the player is near the origin of the world, but as the player approaches each side of the world, it starts to malfunction. Here's a gif showing that interaction: https://imgur.com/gallery/WKtGUs8
Basically as I move to the right I can't shoot to the left, up I cant shoot down, etc. I would appreciate any help, thanks in advance!
Start Use for initialization
Update is called once per frame void Update() { cam = Camera.main; Vector3 mouse = cam.ScreenToWorldPoint(Input.mousePosition);
mouse.z = 0; Vector2 moveVelocity = mouse.normalized * bulletSpeed; rb.AddForce(moveVelocity); }
I'm aware it's in the start function, that's not the issue here since each instance of the script only needs the mouse position once because it's instantiating a new GameObject. Everything works perfectly until I move away from the origin of the world.
Answer by hexagonius · Dec 04, 2018 at 06:43 AM
you're using the mouse position only. subtract the player position from it and normalize the result (mouse - player, normalize)
Your answer
Follow this Question
Related Questions
Box and circle Collider doesn't work 1 Answer
Orbital cannon jitters while following/facing mouse position 1 Answer
Player is not moving 0 Answers
Need Help with MousePos and dashing 0 Answers
How to Create a Launch Path? 2 Answers