Space Shooter之飞船的运动、边界控制和运动旋转

Space Shooter之飞船的运动、边界控制和运动旋转_第1张图片Space Shooter之飞船的运动、边界控制和运动旋转_第2张图片


代码清单如下:

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().velocity = movement * speed;


        // 添加边界 position, Clamp
        GetComponent().position = new Vector3
            (
                Mathf.Clamp(GetComponent().position.x, xMin, xMax),
                0.0f,
                Mathf.Clamp(GetComponent().position.z, zMin, zMax)
            );

        // 运动时旋转 rotation
        GetComponent().rotation = Quaternion.Euler(0.0f, 0.0f, GetComponent().velocity.x * -tilt);

	}
}

总结:控制GameObject的物理运动,基于刚体!

1. 飞船游戏对象的运动,通过物理的刚体来控制,获得已经添加刚体的游戏对象即飞船;给飞船的velocity赋值即可使之运动。

2. 同样基于刚体,获得飞船的位置,GetComponent().position.x表示飞船在x轴上的位置,clamp函数返回的是在xMin和xMax之间的飞船的位置;即飞船的位置介于这两个值之间,所以飞船是飞不出屏幕的;

3. 控制旋转,同样是基于刚体,首先通过GetComponent()获取游戏对象,即飞船,然后飞船的velocity、position和rotation参数就可以相应的控制了。


你可能感兴趣的:(Unity学习札记)