统一将物体移动到右/左侧

时间:2016-09-28 20:56:07

标签: unity3d touch

我是团结的新手,我正在尝试做一个简单的任务:触摸一个物体,然后释放你的触摸。当你发布时,我想检查你触摸屏幕的哪一侧,然后将对象移动到屏幕的那一侧。 因此,如果我按下我的物体,然后将手指向上移动到右侧,物体将向左移动并向右侧移动......

这是我的代码,附加到游戏对象,由于某种原因,对象只是到了屏幕的右侧。即使我使用了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);
    }
}
谢谢你!

2 个答案:

答案 0 :(得分: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));
        }
    }

不确定Ray的演员会做什么,如果有人可以解释,我会很高兴。

答案 1 :(得分:0)

你的代码几乎是正确的。您只需要定义目标位置,并且每次都在更新函数中调用Lerp。

一个简单的解决方案是将两个空对象定义为位置目标,并将它们作为参数传递给函数。

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