- Home /
rotate character in 2.5D
Hi all,
I am trying to learn character controller in Unity3D, i have a basic setup of platform (similar to 2d platform tutorial provided with unity), and character, my character move through character controller in right/left direction when i press right/left arrow key, now i want my character to rotate towards the arrow direction (i.e. face towards right when i press right key & face left when i press left arrow key).
i want my character to move in only left/right direction, and not in z axis. i am unable to figure out how to do that with c# script.
my code attached with character is as follow -
public class PlayerController : MonoBehaviour { public float speed = 6.0F; public float jumpSpeed = 8.0F; public float gravity = 20.0F; private Vector3 moveDirection = Vector3.zero; CharacterController controller; void OnControllerColliderHit (ControllerColliderHit hit) { if(hit.collider.name == "pickup_coin"){ Destroy(hit.collider.gameObject); } } // Update is called once per frame void Update () { controller = GetComponent(); if (controller.isGrounded) { moveDirection = new Vector3(0,0,Input.GetAxis("Horizontal")); moveDirection = transform.TransformDirection(moveDirection); moveDirection *= speed; if (Input.GetButton("Jump")) moveDirection.y = jumpSpeed; } moveDirection.y -= gravity * Time.deltaTime; manageAnimation(); controller.Move(moveDirection * Time.deltaTime); transform.position = new Vector3(transform.position.x, transform.position.y, 0); // make sure it will always remain in 0 @ z-depth. } /// /// Manages the animation's state according to speed. /// private void manageAnimation() { if(!controller.isGrounded){ animation.CrossFade("jump"); }else{ if(moveDirection.x != 0){ Debug.Log(transform.rotation.eulerAngles.y); animation.CrossFade("walk"); if(moveDirection.x > 0 && transform.rotation.eulerAngles.y != 90){ transform.Rotate(0, 90, 0); }else if(moveDirection.x < 0 && transform.rotation.eulerAngles.y != 270.0f){ transform.Rotate(0, 270, 0); } }else{ animation.CrossFade("idle"); } } } }
Answer by Radon · Aug 03, 2012 at 03:06 AM
Try rotation at every unit.
function Update() {
if(Input.GetAxis ("Horizontal") || Input.GetAxis ("Vertical"){
transform.Translate(x, y, z); // change x, y, z with #s
}
}
Hi @Radon, thanks for input, above code will move character in all the direction, but i wanted to restrict it in x direction only.
anyway, i really appreciate your effort for jumping into such a lengthy question.
now i got my answer by myself, ins$$anonymous$$d of rotation character, i make that character a child of empty game object, & applied script onto it, now i am only rotation child character, that thing worked for me. thanks once again for your kind suggestion.