Unity3D角色移动控制脚本
- 键盘控制方向
- 鼠标控制方向
键盘控制方向
private CharacterController controller;
public float Speed = 1f;
public float RotateSpeed = 1f;
void Start(){
controller = transform.GetComponent<CharacterController>();
}
void Update(){
//键盘控制
Move();
//鼠标控制
MoveMouse();
}
private void Move(){
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
var move = transform.forward * Speed * vertical * Time.deltaTime;
controller.Move(move);
transform.Rotate(Vector3.up, horizontal * RotateSpeed);
}
鼠标控制方向
private void MoveMouse(){
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
var direction = new Vector3(horizontal, 0, vertical).normalized;
var move = direction * Speed * Time.deltaTime;
controller.Move(move);
var playerScreenPoint = Camera.main.WorldToScreenPoint(transform.position);
var point = Input.mousePosition - playerScreenPoint;
var angle = Mathf.Atan2(point.x, point.y) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(transform.eulerAngles.x, angle, transform.eulerAngles.z);
}