- Home /
I can get a sprite to look at my mouse but not another Vector3, im not doing anything wrong but the sprite just looks in one direction.
I want a sprite to follow my player and i found some code to follow my mouse and the sprite looked at it wherever he was, however, when i changed out the variable for the mouse position to t, he vector3 storing my players location it looks in one direction, not even a point. I dont knwo what im doing wrong. Here are the two bits of code, firstly the one that tracks my mouse.
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
//transform.LookAt(new Vector3(mousePosition.x, mousePosition.y, transform.position.x)); <---- THIS LINE WAS COMMENTED OUT BUT IT WORKS EITHER WAY
Quaternion rot = Quaternion.LookRotation( transform.position - mousePosition, Vector3.forward );
transform.rotation = rot;
And here is the edited code for following my sprite.
var mousePosition = shipLoc;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.LookAt(new Vector3(heroX, heroY, -10));
var rot = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward );
transform.rotation = rot;
transform.eulerAngles = new Vector3(0, 0,transform.eulerAngles.z);
Answer by robertbu · Mar 19, 2014 at 09:33 PM
Assuming 'shipLoc' is a world position, you need to delete the second line in your second code fragment. ScreenToWorldPoint() translates the screen pixels into a world position. You don't need that if 'shipLoc' is a world coordinate.
@robertbu Deleted that line and the enemy stares in a different direction but still doesnt follow me. :(
'shipLoc must be a Vector3? If so, how do you update its value. A better solution would be to make 'shipLoc' a Transform. You would initialize it through drag and drop. Then you would do this:
var mousePosition = shipLoc.position;
Vector3s are structs not classes. You access them by value ins$$anonymous$$d of by reference. That means that 'shipLoc' is not being updates as you move.
I tried this, and now my enemy will only look left or right.
Your answer
![](https://koobas.hobune.stream/wayback/20220613140701im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Camera follow 2D sprite when it goes off screen 1 Answer
LookAt To Only Rotate on Y Axis 2 Answers
Can anyone please tell me why this script doesnt work? - Raycasting 1 Answer
Camera Follow Object While Looking At Other Target 2 Answers
My AI code is only making a sprite look Left or Right? Help please. 1 Answer