【问题标题】:how do i move a object with direction of touch unity我如何移动具有统一触摸方向的对象
【发布时间】:2016-12-15 05:13:33
【问题描述】:

我是游戏开发的初学者。我正在开发一个游戏,我有一个球,我想通过触摸来移动它。我希望它像足球比赛一样移动,球可以在触摸的方向移动。

但是,现在它似乎只能朝着前进的方向前进!这是我的代码:

 public float ThroughSpped;
 public float ArchSpped;
void OnMouseDown() {

         distance = Vector3.Distance (transform.position, Camera.main.transform.position);
         Dragging = true;

     }
     public void OnMouseUp()
     {
         //Instantiate(this) ;
         this.GetComponent<Rigidbody> ().useGravity = true;



     this.GetComponent<Rigidbody> ().velocity += this.transform.forward*ThroughSpped;
         this.GetComponent<Rigidbody> ().velocity += this.transform.up*ArchSpped;
         Dragging = false;

     }

 void DraggingBall()
 {
     if (Dragging) 
     {
         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
         Vector3 raypoint = ray.GetPoint (distance);
         transform.position = Vector3.Lerp (this.transform.position, raypoint, Speed * Time.deltaTime);
         Destroy(BallPrefabClone, 1f);
     }
 }

【问题讨论】:

  • 你的球只向前移动吗..是不是像扔 pokeball 一样?

标签: c# unity3d


【解决方案1】:

您可以使用触摸相位来获取触摸的开始位置和触摸的结束位置来计算触摸的矢量/方向

然后使用这个新向量为你的球添加力量

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public Vector2 startPos;
    public Vector2 direction;
    public bool directionChosen;
    void Update()
    {
        // Track a single touch as a direction control.
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            // Handle finger movements based on touch phase.
            switch (touch.phase)
            {
                // Record initial touch position.
                case TouchPhase.Began:
                    startPos = touch.position;
                    directionChosen = false;
                    break;

                // Determine direction by comparing the current touch position with the initial one.
                case TouchPhase.Moved:
                    direction = touch.position - startPos;
                    break;

                // Report that a direction has been chosen when the finger is lifted.
                case TouchPhase.Ended:
                    directionChosen = true;
                    break;
            }
        }
        if (directionChosen)
        {
            // Something that uses the chosen direction...
        }
    }
}  

https://docs.unity3d.com/ScriptReference/Touch-phase.html

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多