简单的角色移动,使用CharacterController控制器,参加如下代码
using UnityEngine;
using System.Collections;
public class example : 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(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}// This script moves the character controller forward
// and sideways based on the arrow keys.
//这个脚本用箭头键向前移动和侧移角色控制器。
// It also jumps when pressing space.
//当按下空格键时,它跳起。
// Make sure to attach a character controller to the same game object.
//确保把一个character controller组件附加到同一个游戏物体上。
//It is recommended that you make only one call to Move or SimpleMove per frame.
//建议你每帧只调用一次Move或者SimpleMove。
var speed : float = 6.0;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
private var moveDirection : Vector3 = Vector3.zero;
function Update() {
var controller : CharacterController = GetComponent(CharacterController);
if (controller.isGrounded) {
// We are grounded, so recalculate
// move direction directly from axes
//我们着地了,所以直接通过轴重新计算move direction。
moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
// Apply gravity
//应用重力。
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
//移动控制器。
controller.Move(moveDirection * Time.deltaTime);
}
【注意】
1、如果想让角色控制器推开其他刚体或者对象,你可以在对象附加的脚本中添加OnControllerColliderHit()函数,这样对它们施加力就能够产生碰撞。
2、另外,如果你想让你的游戏角色被物理效果影响,那就最好使用刚体而不是角色控制器。
3、如果发现你的角色频繁被卡住,尝试调整SkinWidth值,实践中比较好的值是至少要大于0.01并且大于Radius的10%。
4、transform.TransformDirection();获取此对象的世界坐标方向,使它朝着自身的某一方向移动// and sideways based on thearrow keys.
1万+



被折叠的 条评论
为什么被折叠?



