Unity ~フリック距離取得~

| Script


 

Unity において、スマホのフリックの挙動を利用して、ゲームなどのパラメータの強弱を決める方法。

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarController : MonoBehaviour {

    float speed = 0;
    float swipeLength = 0;
    Vector2 startPos;
    Vector2 endPos;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetMouseButtonDown(0))
        {
            this.startPos = Input.mousePosition;
        } 
       else if (Input.GetMouseButtonUp(0)) 
     {
            this.endPos = Input.mousePosition;

            this.swipeLength = (this.endPos.x - this.startPos.x);

            this.speed = swipeLength / 500.0f;

         }

        transform.Translate(this.speed, 0, 0);

        this.speed *= 0.98f;
	}
}

 

ここでは、フリックの始点を、Input.GetMouseButtonDown(0) で表現し、終点を、Input.GetMouseButtonUp(0) で表している。

 

その中で、それぞれの座標を、Input.mousePosition で取得し、startPos と endPos に格納している。

 

このスクリプトでは、それぞれの Vector2型の変数 startPos と endPos のx座標だけを取り出し、差を求めることで、フリックの距離を取得している。

 

何かと、スマホゲームの製作時には重宝しそうだ。

 

コメント

タイトルとURLをコピーしました