您的位置:首页 > 产品设计 > UI/UE

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

2016-07-14 09:35 471 查看
上一篇文章已经搭建起来游戏场景了,接下来将要使这些对象动起来。

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

这个网站解决了大家开始设计阶段的问题,轻量级的各种设计模型,强烈推荐
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  u3d ugui game