您的位置:首页 > 其它

【Space Shoot Project】moving the player

2015-10-27 21:38 633 查看
本节主要控制发射子弹的飞船

1. Assets folder中添加 Script文件夹,存放代码

2. 选中Player,Add Component - > Scripts 重命名为 PlayerController,(注意此处两个字母的大写,scripts 名字需要以大写字母开头)

3. 打开代码文件,update 是每帧渲染需要之行的代码

rigidbodies 可以用来控制物理属性,比如碰撞,重力等





由于只需要在X,Z二维控制ship,分别为 左右(Horizontal),上下(Vertical)。Y固定设置为0

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);


input (0~1), 需要一个speed 来控制速度

控制ship 运动的范围,不要走出去了。y设置为0, X,Z 使用mathf.clamp (Ctrl+'在 文档中可查看)(取在min, max 之间的值)

定义一个Boundary类,在update函数中定义一个实例 boundary

[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}


Systerm.Serializable 可以方便在 inspector 中看到 boundary





最后的欧拉旋转,为了增强既视感,越快,Z轴 ship 会有个偏转。这样表面的反射光也会有所不同,立体感更强

完整的代码如下所示:

using UnityEngine;
using System.Collections;

[System.Serializable] public class Boundary { public float xMin, xMax, zMin, zMax; }

public class PlayerController : MonoBehaviour
{
public float speed;
public float tilt;
public Boundary boundary;

void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rigidbody.velocity = movement * speed;

rigidbody.position = new Vector3
(
Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
);

rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: