- Home /
Top down camera player rotating
So I've got a script which makes the player rotate where the mouse is. I'm just wondering if theres a way to lock an axis. Because when the mouse goes over the player model the model rotates and faces straight up.
var speed : float = 20.0;
var rotatespeed : float = 2.0;
function Update() {
var controller : CharacterController = GetComponent(CharacterController);
transform.Rotate(0,Input.GetAxis("Horizontal") * rotatespeed, 0);
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var currentspeed : float = speed* Input.GetAxis("Vertical");
controller.SimpleMove(forward * currentspeed);
var position = Input.mousePosition;
var newposition = Vector3(position.x, position.y, camera.main.transform.position.y- transform.position.y);
var lastposition = camera.main.ScreenToWorldPoint(newposition);
transform.LookAt(lastposition);
}
Yeah its 2D, I've had the problem with fixed camera and smooth follow
Did the answer from robertbu solve your problem? If so please accept the answer to mark your question as solved. If it didn't tell us how it didn't.
Answer by robertbu · Mar 23, 2013 at 09:58 PM
This is a bit of untested modification to your code. Instead of forward, it uses right, so the right side of your object should track the mouse. If you need 'Z' to track, apply this script to an empty game object and then make the visible game object a child with the correct rotation.
#pragma strict
var speed : float = 20.0;
var rotatespeed : float = 2.0;
function Update() {
var controller : CharacterController = GetComponent(CharacterController);
transform.Rotate(0,Input.GetAxis("Horizontal") * rotatespeed, 0);
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var currentspeed : float = speed* Input.GetAxis("Vertical");
controller.SimpleMove(forward * currentspeed);
var position = Input.mousePosition;
var newposition = Vector3(position.x, position.y, camera.main.transform.position.y- transform.position.y);
var lastposition = camera.main.ScreenToWorldPoint(newposition) - transform.position;
var angle : float = Mathf.Atan2(lastposition.z, lastposition.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
}
I get this error trying to use it "Assets/Scripts/Player.js(18,37): BCE0005: $$anonymous$$ identifier: 'lookPos'."
Should have been 'lastposition'. Code was copied and modified from elsewhere.
Your answer
Follow this Question
Related Questions
Top Down Shooter Help 1 Answer
How To Get Object To Aim at Mouse in Top Down 3D Shooter 4 Answers
C# LookAt Mouse 2D 2 Answers
Lock a rotation 1 Answer
Lock the y axis (on an object that's not a rigid body) c# 0 Answers