Hello i have a player in my game and Im trying to make it rotate towards where the mouse is facing, but the model itself doesnt rotate and I’m getting no errors what so ever how would i make the model rotate towards the cursor location(This is a Diablo style game with a 3D yet 2D view). This is an overhead style game so it has to rotate on a horizontal plane aka the x axis. I need it so that when the mouse is to the left of the player it sends the Vector3 up, and when the mouse is to the right of the player it sends it down. How would i do this?
using UnityEngine;
using System.Collections;
public class SCR_mouseRotation : MonoBehaviour {
void Update () {
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.z, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.down); // Turns Right
transform.rotation = Quaternion.AngleAxis(angle, Vector3.up); //Turns Left
}
}
This script is really buggy does anyone else have any better suggestions to make the player rotate towards the mouse location?
[37154-looktowardmouse.unitypackage.zip|37154]There’s lots of ways, but here’s an easy one:
public class LookTowardMouse : MonoBehaviour {
// Update is called once per frame
void Update ()
{
//Get the Screen positions of the object
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint (transform.position);
//Get the Screen position of the mouse
Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
//Get the angle between the points
float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen);
//Ta Daaa
transform.rotation = Quaternion.Euler (new Vector3(0f,0f,angle));
}
float AngleBetweenTwoPoints(Vector3 a, Vector3 b) {
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
}
public class LookTowardMouse : MonoBehaviour {
void Update ()
{
//Mouse Position in the world. It's important to give it some distance from the camera.
//If the screen point is calculated right from the exact position of the camera, then it will
//just return the exact same position as the camera, which is no good.
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * 10f);
//Angle between mouse and this object
float angle = AngleBetweenPoints(transform.position, mouseWorldPosition);
//Ta daa
transform.rotation = Quaternion.Euler (new Vector3(0f,0f,angle));
}
float AngleBetweenPoints(Vector2 a, Vector2 b) {
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
}
My answers keep disappearing. Anyway, this is a correction from the last one.
Is there anyway to make this turn the player the full 360 degrees? Im really new to unity and game dev in general so the answer is probably really obvious, im just to much of a noob to spot it, any help would be greatly appreciated.