unity3D技术分享

EasyTouch5控制物体平滑的移动

2018-09-05  本文已影响0人  小黑Unity_齐xc
b.gif

通过手指触摸屏幕,控制物体流畅的移动,物体速度与手指速度一致。

1.创建场景

image.png

1.1新建空物体,命名player
1.2创建子物体img和trail
1.3img上renderer指定一个圆形材质即可
1.4trail添加Trail Renderer组件,配置如下:


image.png

1.5场景中加入EasyTouch对象

2.手指触摸屏幕控制物体的移动

2.1 为player对象创建脚本 PlayerMove.cs
2.2 编写脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HedgehogTeam.EasyTouch;

public class PlayerMove : MonoBehaviour {
    Rigidbody2D rigidbody;

    public float velocity_x = 0;
    public float velocity_y = 0;

    private float width;
    private float height;

    void Awake(){
        rigidbody = GetComponent<Rigidbody2D> ();
        rigidbody.velocity = new Vector2 (velocity_x,velocity_y);

                //根据相机尺寸获得屏幕宽高
        Camera cam = Camera.main;
        height = 2f * cam.orthographicSize;
        width = height * cam.aspect;
    }

    void Update(){
                //Easy Touch事件监听
        Gesture curGesture = EasyTouch.current;
        if(curGesture==null){
            return;
        }
        if(curGesture.type == EasyTouch.EvtType.On_TouchStart){
            On_TouchStart (curGesture);
        }
        else if(curGesture.type == EasyTouch.EvtType.On_TouchDown){
            On_TouchDown (curGesture);
        }
        else if(curGesture.type == EasyTouch.EvtType.On_TouchUp){
            On_TouchUp (curGesture);
        }
    }

    void On_TouchStart(Gesture gesture){
    }

    void On_TouchDown(Gesture gesture){
                //计算手指划过位移与屏幕的比率
        float temp_x = gesture.deltaPosition.x / width * 2;
        float temp_y = gesture.deltaPosition.y / height * 2;
                //指定速率
        rigidbody.velocity = new Vector2 (temp_x, temp_y);
    }

    void On_TouchUp(Gesture gesture){
                //恢复默认速率
        rigidbody.velocity = new Vector2 (velocity_x,velocity_y);
    }
}

  1. 设置物体的刚体组件
    3.1 player增加rigidbody2d组件
    3.2修改刚体属性


    image.png

运行,即可得到顶部图片的效果。

上一篇 下一篇

猜你喜欢

热点阅读