- Home /
Rotate to facing direction 2.5D
Does anyone know how to get a character to rotate and move in the direction of the key they press?
Like pressing the left key makes the character look left and move that way?
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
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;
controller.Move(moveDirection * Time.deltaTime);
}
}
I tried this
else if (Input.GetKeyDown(KeyCode.A))
transform.forward = new Vector3(1f, 0f, 0f);
else if (Input.GetKeyDown(KeyCode.D))
transform.forward = new Vector3(-1f, 0f, 0f);
The turning direction is fixed but it still moves in only one direction.
[Edit Berenger : Code formatting]
Answer by Berenger · Mar 05, 2012 at 04:50 PM
Affect moveDirection to the forward, not a new Vector3. If you want the rotation to happen slower, use Vector3.Lerp( transform.forward, moveDirection, Time.deltaTime * rotSpeed ), or even Mathf.Lerp, as your game isn't 3D you will only need one axe.
Basically you are still using the same positive and negative axis directions with your horizontal axis, and translating them into local space, but they're still the same direction. Thus, use its forward axis, which you're already flipping by turning it, so you don't need the horizontal axis' positive or negative sign.
Answer by dowsodsai · Mar 06, 2012 at 11:31 PM
still have no idea...
am really stupid about these Vector3
Can you provide a sample code please or fix these error ? I really can't figure this out
sorry and thank for your help