消灭星星(二)让主角动起来

7 篇文章 0 订阅

上一篇文章已经搭建起来游戏场景了,接下来将要使这些对象动起来。
u3d有新的自带的动画编辑器,也有第三方插件的方式来进行动画,我们选择使用第三方插件的模式,DoTween动画插件。u3d本身的动画系统稍微比这个复杂一些,也没有这么直观。好了,首先需要下载一个DoTween插件,然后把它拖拽到项目的asset中。

接下来我们要给主角绑定一个脚本,让主角动起来
1 在asset中新建一个folder,命名为Scripts这个文件夹用来存放脚本
这里写图片描述
2在Scripts文件夹中新建C#脚本,命名为Player
这里写图片描述

这里写图片描述

3 在Player.cs中添加代码,绑定界面中的主角对象,并对其进行控制

引入DoTween

using DG.Tweening;      // 引入DoTween
public class Player : MonoBehaviour {
    public GameObject _playerObj;   // 要绑定的主角对象

    private Transform _trans;
    private float _jumpHieght = 100; //主角跃的高度
    private float _jumpWidth  = 100; //主角跳跃的宽度
    private float _during = 0.3f;    // 跳跃所花费的时间
    private bool _isJumpping = false; // 是否正在跳跃状态
    // Use this for initialization

    void Awake(){
        this._trans = _playerObj.GetComponent<Transform> ();  // 获取对象的transform组件
    }
    // Update is called once per frame
    void Update () {
        if (Input.GetKey (KeyCode.LeftArrow)) {  // 左键向左跳
            this.move (true);
        }
        else if(Input.GetKey (KeyCode.RightArrow)){  // 右键向右跳
            this.move (false);
        }
    }
    // 主角跳跃函数
    public void move(bool left){
        if (this._isJumpping) {   // 当前正在跳跃中则不执行此指令
            return;
        }
        this._isJumpping = true;
        float x = this._jumpWidth / 2;
        if (left) {
            x = x * -1;
        }
        float x1 = x;
        // u3d中对象的位置是通过Transform组件的postion修改来实现的
        if (this._trans.localPosition.x + x <= -290) {  // 规定不能超过屏幕的可视范围
            x = -290 - this._trans.localPosition.x;
            x1 = 0;
        } else if (this._trans.localPosition.x + x >= 300) {
            x = 300 - this._trans.localPosition.x;
            x1 = 0;
        }
        // DoTween函数,在一定时间内移到到指定位置
        Tweener tw = this._trans.DOMove (new Vector3 (this._trans.position.x + x,
                         this._trans.position.y + this._jumpHieght, 0), this._during);
        // 向上跳部分结束,调用结束函数
        tw.OnComplete(()=>this.onJumpUpEnd(x1));
    }
    // 向上跳结束,开始下落
    void onJumpUpEnd(float x){
        this._trans.DOMove (new Vector3(this._trans.position.x + x,
            this._trans.position.y - this._jumpHieght, 0), this._during).OnComplete(this.onJumpDownEnd);
    }
    // 整个过程结束,主角回到地面
    void onJumpDownEnd(){
        this._isJumpping = false;
    }
}

4 选中我们的主角UI,然后把刚刚的脚本拖拽到此UI中,并把主角UI拖拽进刚刚在脚本中定义的gameobject。
这里写图片描述

5 运行游戏,并按键盘上的左或右键,就能看到主角动起来了!

https://www.processon.com/i/568c6ea4e4b0e51d149a085f
这个网站解决了大家开始设计阶段的问题,轻量级的各种设计模型,强烈推荐

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值