代码清单如下:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
public float xMin, xMax, zMin, zMax;
public float tilt;// 旋转因子
void Update () {
// 使得飞船运动 velocity
float moveHorizontal = Input.GetAxis("Horizontal");// 获取键盘的垂直和水平方向
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
GetComponent<Rigidbody>().velocity = movement * speed;
// 添加边界 position, Clamp
GetComponent<Rigidbody>().position = new Vector3
(
Mathf.Clamp(GetComponent<Rigidbody>().position.x, xMin, xMax),
0.0f,
Mathf.Clamp(GetComponent<Rigidbody>().position.z, zMin, zMax)
);
// 运动时旋转 rotation
GetComponent<Rigidbody>().rotation = Quaternion.Euler(0.0f, 0.0f, GetComponent<Rigidbody>().velocity.x * -tilt);
}
}
总结:控制GameObject的物理运动,基于刚体!
1. 飞船游戏对象的运动,通过物理的刚体来控制,获得已经添加刚体的游戏对象即飞船;给飞船的velocity赋值即可使之运动。
2. 同样基于刚体,获得飞船的位置,GetComponent<Rigidbody>().position.x表示飞船在x轴上的位置,clamp函数返回的是在xMin和xMax之间的飞船的位置;即飞船的位置介于这两个值之间,所以飞船是飞不出屏幕的;
3. 控制旋转,同样是基于刚体,首先通过GetComponent<Rigidbody>()获取游戏对象,即飞船,然后飞船的velocity、position和rotation参数就可以相应的控制了。
本文介绍了一个Unity中的飞船控制脚本,该脚本使用刚体组件控制飞船的移动与旋转,并设置了边界限制以防止飞船飞出屏幕。
7205

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



