I'm making a 2.5d side scrolling shooter and I use the mouse to aim the weapons that he has. What I would like to do is have the character rotate to face whichever side of him that the mouse is on. I have tried the standard lookat scripts but I do not want his entire body to look up and down, I want the Y axis limited so that it doesn't make him look up or down, only 90 degrees forward or backward. Because the game is 2.5d I also need him to look straight ahead of where he is on the z axis. Here is a graphical presentation of what I need help with. (limited Unity scripting knowledge too, sorry)
This can be done fairly simply by transforming the point the mouse is pointing at into local space and then checking if it changed from positive to negative and then changing the facing.
FlipFacing.js (attached to the thing you want to turn around)
function Update() {
var target : Vector3 = Input.mousePosition;
target.z = sceneDepth; //Decide how far into the scene to aim at.
target = Camera.main.ScreenToWorldPoint(target);
if(transform.InverseTransformPoint(target).z < 0.0f) TurnAround();
//Do other stuff
}
function TurAround() {//What you do here depends on your setup
//To simply flip, you could do:
//transform.forward = -transform.forward;
//or
transform.LookAt(tranform.position-transform.forward);
//or transform.eulerAngles.y += 180.0f;
//or if you have an animation for turning, play that here
//animation.Play("Turn around");
}
If your turn takes time, you'll want to add a check for whether you are turning in the if statement before you call transform.InverseTransformPoint or inside TurnAround and then adjust appropriately.