Unity入门操作_ 角色控制器_015

CharacterController
编写第一人称控制器

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour {

CharacterController _characterController;
Rigidbody _rigidbody;

float _horizontal;
float _vertical;
Vector3 direction;

public float speed = 1;
public float jumpPower = 5;

// Use this for initialization
void Start () {

    _characterController = this.GetComponent();
    _rigidbody = this.GetComponent();
}
// Update is called once per frame
void Update () {

    _horizontal = Input.GetAxis("Horizontal");
    _vertical = Input.GetAxis("Vertical");

    if(_characterController.isGrounded)
    {
        direction = new Vector3(_vertical, 0, _horizontal * -1);
        if (Input.GetKeyDown(KeyCode.Space))
        {
            direction.y = jumpPower;
        }
    }

    direction.y -= 5 * Time.deltaTime;
    _characterController.Move(direction * Time.deltaTime * speed);
}

}
using UnityEngine;
using System.Collections;

[RequireComponent (typeof(CharacterController))]
[RequireComponent (typeof(Rigidbody))]
public class CharactorMove : MonoBehaviour {

//移动的速度
public float speed;
//鼠标的水平偏移量
float offsetMouseX;
//鼠标在竖直方向上的偏移量
float offsetMouseY;
//人称控制器在水平方向上的旋转角度
public float rotateX;
private CharacterController m_CharacterController;
private float horizontal;
private float vertical;
private Camera m_mianCamera;
// Use this for initialization
void Start () {
    m_CharacterController = GetComponent();
    m_mianCamera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent();
}

// Update is called once per frame
void Update () {
    horizontal = Input.GetAxis("Horizontal");
    vertical = Input.GetAxis("Vertical");

    //控制第一人称控制器的移动效方向
    Vector3 direction = (transform.forward * vertical + horizontal * transform.right).normalized;
    m_CharacterController.SimpleMove(direction * speed * Time.deltaTime);
    //第一人称控制器左右旋转(此时是游戏界面的二维向量坐标)
    offsetMouseX = Input.GetAxis("Mouse X");
    m_CharacterController.transform.Rotate(Vector3.up * offsetMouseX * rotateX * Time.deltaTime);
    //第一人称控制器抬头低头看(此时是游戏界面的二维向量坐标)
    offsetMouseY = Input.GetAxis("Mouse Y");
    Vector3 cameraRotateAngle = -offsetMouseY * Vector3.right;
    m_mianCamera.transform.eulerAngles += cameraRotateAngle;
}

}

你可能感兴趣的:(Unity,unity)