您的位置:首页 > 移动开发 > Unity3D

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

2017-08-22 20:12 441 查看
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<CharacterController>();
_rigidbody = this.GetComponent<Rigidbody>();
}
// 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<CharacterController>();
m_mianCamera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}

// 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