Unity3D摇杆
Unity3D摇杆
本章博文的目的是利用上一章介绍的游戏摇杆来控制人物模型的移动(见 ),与行走动画的播放。
如上图所示Create中的文件夹male中存放着模型动画与贴图等,这个应该是美术提供给我们的。然后将整个male用鼠标拖动到左侧3D世界中,通过移动,旋转,缩放将人物模型放置在一个理想的位置。右侧红框内设置模型动画的属性。
Animation
idle1 该模型默认动画名称为idle1
Animations
size 该模型动画的数量
Element 该模型的动画名称
Play Automatically 是否自动播放
Animation Physics 是否设置该模型物理碰撞
Animation Only if Visable 是否设置该模型仅自己显示
给该模型绑定一个脚本Controller.cs 用来接收摇杆返回的信息更新模型动画。
Controller.cs
- using UnityEngine;
- using System.Collections;
- public class Controller : MonoBehaviour {
- //人物的行走方向状态
- public const int HERO_UP= 0;
- public const int HERO_RIGHT= 1;
- public const int HERO_DOWN= 2;
- public const int HERO_LEFT= 3;
- //人物当前行走方向状态
- public int state = 0;
- //备份上一次人物当前行走方向状态
- //这里暂时没有用到
- public int backState = 0;
- //游戏摇杆对象
- public MPJoystick moveJoystick;
- //这个方法只调用一次,在Start方法之前调用
- public void Awake() {
- }
- //这个方法只调用一次,在Awake方法之后调用
- void Start () {
- state = HERO_DOWN;
- }
- void Update () {
- //获取摇杆控制的方向数据 上一章有详细介绍
- float touchKey_x = moveJoystick.position.x;
- float touchKey_y = moveJoystick.position.y;
- if(touchKey_x == -1){
- setHeroState(HERO_LEFT);
- }else if(touchKey_x == 1){
- setHeroState(HERO_RIGHT);
- }
- if(touchKey_y == -1){
- setHeroState(HERO_DOWN);
- }else if(touchKey_y == 1){
- setHeroState(HERO_UP);
- }
- if(touchKey_x == 0 && touchKey_y ==0){
- //松开摇杆后播放默认动画,
- //不穿参数为播放默认动画。
- animation.Play();
- }
- }
- public void setHeroState(int newState)
- {
- //根据当前人物方向 与上一次备份方向计算出模型旋转的角度
- int rotateValue = (newState - state) * 90;
- Vector3 transformValue = new Vector3();
- //播放行走动画
- animation.Play("walk");
- //模型移动的位移的数值
- switch(newState){
- case HERO_UP:
- transformValue = Vector3.forward * Time.deltaTime;
- break;
- case HERO_DOWN:
- transformValue = -Vector3.forward * Time.deltaTime;
- break;
- case HERO_LEFT:
- transformValue = Vector3.left * Time.deltaTime;
- break;
- case HERO_RIGHT:
- transformValue = -Vector3.left * Time.deltaTime;
- break;
- }
- //模型旋转
- transform.Rotate(Vector3.up, rotateValue);
- //模型移动
- transform.Translate(transformValue, Space.World);
- backState = state;
- state = newState;
- }
- }
评论暂时关闭