教程地址(观看视频需翻墙):
1.键盘控制物体左右移动
public class PlayerMovement : MonoBehaviour
{
[SerializeField] //在属性窗口可以观察数值变化,也可修改数值
private float _speed;
[SerializeField]
private float _horizontalInput;
void Update()
{
_horizontalInput = Input.GetAxis("Horizontal"); //获取键盘键入信息
transform.Translate(new Vector3(_horizontalInput, 0, 0) * _speed * Time.deltaTime);
}
}
2. 碰撞体应用,被Player碰撞后消失
被撞物体需要添加Trigger和Rigidbody
public class Collectable : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player") //Player的Tag一定要设置成Player才行
{
Destroy(this.gameObject);
}
}
}
3. 暂停和启动游戏,按空格键暂停,按R键启动
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Time.timeScale = 0;
}
if (Input.GetKeyDown(KeyCode.R))
{
Time.timeScale = 1;
}
}