2016-09-28 8 views
1

私は統一されていないので、簡単な作業をしようとしています。オブジェクトに触れてからタッチを離します。あなたが解放するとき、私はあなたがあなたのタッチを解放した画面のどちら側を確認し、次に画面のその側にオブジェクトを移動したい。 私のオブジェクトを押すと、指の先にスワイプして、オブジェクトは左に移動し、右側にも同じように移動します。オブジェクトを左右に動かす

これはゲームオブジェクトに添付された私のコードです何らかの理由でオブジェクトが画面の右側に移動しているに違いない。私がLerpを使っても、それはすばらしいことです。

void OnMouseUp() 
{ 
    Vector3 pos = Input.mousePosition; 

    Debug.Log("press off"); 

    if (pos.x < Screen.width/2) 
    { 
     transform.position = Vector3.Lerp(transform.position, new Vector3(0,0,0), 2f * Time.deltaTime); 
    } 
    else 
    { 
     transform.position = Vector3.Lerp(transform.position, new Vector3(Screen.width, 0, 0), 2f * Time.deltaTime); 
    } 
} 

ありがとう!これを試みるの多くは私のために働いたので、後は

答えて

0

:誰かが説明できる場合

public float smoothing = 7f; 

    IEnumerator MoveCoroutine(Vector3 target) 
    { 
     while (Vector3.Distance(transform.position, target) > 0.05f) 
     { 
      transform.position = Vector3.Lerp(transform.position, target, smoothing * Time.deltaTime); 

      yield return null; 
     } 
    } 

    void OnMouseUp() 
    { 
     Plane p = new Plane(Camera.main.transform.forward, transform.position); 
     Ray r = Camera.main.ScreenPointToRay(Input.mousePosition); 
     float d; 
     if (p.Raycast(r, out d)) 
     { 
      Vector3 target = r.GetPoint(d); 
     if (target.x > 0) 
     { 
      Debug.Log("right:" + target.x + " total: " + Screen.width); 
      target.x = 5; 
      target.y = 0; 
     } 
     else 
     { 
      Debug.Log("left:" + target.x + " total: " + Screen.width); 
      target.x = -5; 
      target.y = 0; 
     } 

      StartCoroutine(MoveCoroutine(target)); 
     } 
    } 

レイキャストが何をするかわからない、私は喜んでいるだろう。

+0

https://docs.unity3d.com/ScriptReference/Physics.Raycast.htmlまたはhttps://www.reddit.com/r/Unity3D/comments/45oj0c/visualization_of/ –

0

あなたのコードはほぼ正しいです。目標位置を定義し、更新機能でLerpが毎回呼び出されるようにするだけです。

単純な解決策は、2つの空のオブジェクトを位置ターゲットとして定義し、それらをパラメータとして関数に渡すことです。

using UnityEngine; 
using System.Collections; 

public class ClickTest : MonoBehaviour { 
    public Transform posLeft; 
    public Transform posRight; 
    private Vector3 destPos; 

    void Setup() 
    { 
     // default target is init position 
     destPos = transform.position; 
    } 

    // Update is called once per frame 
    void Update() { 
     // Define target position 
     if (Input.GetMouseButtonUp (0)) { 
      Vector3 pos = Input.mousePosition; 
      Debug.Log("press off : "+pos+ " scren : "+Screen.width); 

      if (pos.x < Screen.width/2) 
      { 
       Debug.Log("left"); 
       destPos = posLeft.position; 
      } 
      else 
      { 
       Debug.Log("right"); 
       destPos = posRight.position; 
      } 
     } 
     // update position to target 
     transform.position = Vector3.Lerp(transform.position, destPos, 2f * Time.deltaTime); 
    } 
} 

Screenshot with empty objects as parameters

関連する問題