- Home /
About Character Control :D
Hello there~! I am wondering if anyone can tell me why my character always will face forward after finishing of control. Following are my scripts and Thanks in advance!
var moveSpeed = 5.0;
var rotateSpeed = 80.0;
private var controller :CharacterController;
controller = gameObject.GetComponent(CharacterController);
private var moveDirection = Vector3.zero;
private var forward = Vector3.forward;
private var right = Vector3.right;
function Update() {
var x = Input.GetAxis("Horizontal")*Time.deltaTime*moveSpeed;
var z = Input.GetAxis("Vertical")*Time.deltaTime*moveSpeed;
var targetDirection = x * right + z * forward;
transform.Translate(x,0,z,Space.World);
var angle = Mathf.Atan2(x,z)* Mathf.Rad2Deg ;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
}
If you have a better way of controlling it like mine and would like to share it with me, then I will very appreciate it~! :)
If you can also edit the post, select your code.. and press the Code Sample button, to be awesome..
Answer by Jaap Kreijkamp · Mar 15, 2010 at 12:52 AM
Don't understand your question completely but you DON'T want the character face the direction you're moving? Then remove the transform.rotation
line at the end.
If you WANT to have it look in the right direction, you could use transform.LookAt(transform.position + targetDirection, Vector3.up)
, although you should check if targetDirection.sqrMagnitude > 0
. So that would give:
var moveSpeed = 5.0; var rotateSpeed = 80.0; private var controller :CharacterController; controller = gameObject.GetComponent(CharacterController); private var moveDirection = Vector3.zero; private var forward = Vector3.forward; private var right = Vector3.right;
function Update() { var x = Input.GetAxis("Horizontal")*Time.deltaTime*moveSpeed; var z = Input.GetAxis("Vertical")*Time.deltaTime*moveSpeed;
var targetDirection = x * right + z * forward;
transform.Translate(x,0,z,Space.World);
if (targetDirection.sqrMagnitude > 0) {
transform.LookAt(transform.position + targetDirection, Vector3.up);
}
}
Thank you very much~! It is much better now , but still it can only look at 8 directions--(1,0,0),(1,0,1),(0,0,1),(1,0,-1),(0,0,-1),(-1,0,-1),(-1,0,0),(-1,0,1).. Could you please tell me if there is a better solution?
Basically that's a problem of your control setup, if you would use a analogue controller you would see you can actually look in every direction. You can edit under Edit->ProjectSettings->Input the behaviour of the control keys, make the keys react slower (more time to move from centre position to max position).