【Space Shoot Project】moving the player

本节主要控制发射子弹的飞船


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

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

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

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

image

由于只需要在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

image

最后的欧拉旋转,为了增强既视感,越快,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);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不负初心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值