- Home /
rotate Y axis to face mouse
hi, i'm trying having a hard time making a script that will let my character always face the mouse, via the Y axis (top down style) but i am not having any luck. the hard part is that the camera is in a slight tilt so that it's not 100% "top down" (about a 40° tilt) so is there anyway to take the position of the mouse relative to the center of the screen (since the character is always center anyways) and translate that to rotation for the character?
Answer by Xarbrough · Apr 04, 2015 at 10:27 PM
You can go with your approach of getting the vector of your camera to the screen center and then setting your object's facing direction to the same vector. You might need to flip it to the correct orientation and you will have to come up with a solution what to do when the mouse is close to the center, because then it just becomes jittery.
public class RotateByMouse : MonoBehaviour {
public Transform gameObjectToRotate;
Vector3 middleOfScreen;
void Start() {
middleOfScreen = new Vector3(Screen.width/2, Screen.height/2, 0f);
}
void Update() {
Vector3 camVec = Input.mousePosition - middleOfScreen;
Vector3 flipped = new Vector3(camVec.x, 0f, camVec.y);
gameObjectToRotate.LookAt(flipped);
}
}
for some reason your solution gave me a weird offset with the rotation so after i translated it to JS i change it to use vector 2 as the mouse position and middle of the screen and it worked.
var gameObjectToRotate:Transform;
private var middleOfScreen:Vector2;
private var mousePos:Vector2;
private var target:Vector2;
private var flipped:Vector3;
function Start () {
middleOfScreen = new Vector2(Screen.width/2, Screen.height/2);
}
function Update () {
mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
target = mousePos - middleOfScreen;
flipped = new Vector3(target.x, 0f, target.y);
gameObjectToRotate.LookAt(flipped);
}
Weird, I did test my own code and it worked for me, so not sure what could have gone wrong; and I don't see a difference in functionality between your js version and $$anonymous$$e. But glad, that it worked in the end.
Your answer
Follow this Question
Related Questions
Fixed camera on rails. 2 Answers
Move character using Camera Input 2 Answers
Making my look script turn smoothly 0 Answers
Move RigidBody character relative to camera. 2 Answers
Simple way to make an object go up and down?(Y axis) 1 Answer