Player rotating towards mouse 3D
I'm trying to make a top-down in 3d and want my character to rotate towards the mouse position but it only works right when the game starts (the character rotates to wherever my mouse is at the beginning) and then no matter where I move it the character just stays still...
private void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePos - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(-angle, Vector3.up);
}
Any type of support is greatly appreciated, Thanks!
Answer by iKabyLake30 · Feb 13, 2020 at 07:33 PM
Hi, i was looking for exactly same thing and came with this..
moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * moveSpeed;
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if (groundPlane.Raycast(cameraRay, out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
Debug.DrawLine(cameraRay.origin, pointToLook, Color.cyan);
transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
}
Hey, sorry, just wanna make sure, can I use this code?
Answer by unity_ek98vnTRplGj8Q · Feb 14, 2020 at 01:01 AM
The reason you aren't seeing updates is that you need to tell ScreenToWorldPoint
how far away from the camera you want your point to be. If you feed the mouse position in directly, your z value will be zero, indicating that you want a point distance 0 away from you camera. Since your camera is a point, no matter where you put your mouse on the screen it will always return the position of the camera. If you add a z amount to your mouse position
Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0,0,depth);
Then you will start to see your object rotate. Your code above won't quite work though, you need to add an extra check for whether the mouse is above or below your object
Understood, thanks a lot for taking your time and explaining that, this is very helpful.
Your answer
Follow this Question
Related Questions
How to rotate Object with Mouse drag (specifications below) 2 Answers
Problem with creating a Script that let a Object follow my mouse cursor(3D) 0 Answers
Problem with rotation to mouse position 0 Answers
Using a directional vector to orient a sphere? 0 Answers
How to lock X rotation on 3D object? 0 Answers