【问题标题】:Moving an object quickly accros the screen using touch in Unity?在 Unity 中使用触摸在屏幕上快速移动对象?
【发布时间】:2019-02-15 12:50:48
【问题描述】:

我目前正在开发一款游戏,我希望允许玩家使用触摸控件在屏幕上拖动游戏对象。但是,由于某种原因,我的代码不断返回错误(“deltaPosition”在当前上下文中不存在),这不应该发生,因为我从 youtube 视频中获取了代码,它没有显示任何编译错误时该人显示了代码。这是由于新版本的 C# 还是有人知道我如何解决这个问题。谢谢enter image description here

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


    public class PositionTracker : MonoBehaviour
    {
        [SerializeField]
        float                  _horizontalimit = 2.5f, _verticalLimit = 2.5f, dragSpeed = 0.1f;

        Transform cashedTransform;

        Vector3 startingPos;


        void Start()
        {
            cashedTransform = transform;
            startingPos = cashedTransform.position;
        }

        void Update()
        {
            if (Input.touchCount > 0)
            {
                Vector2 deltaPostion = Input.GetTouch(0).deltaPosition;

                switch (Input.GetTouch(0).phase)
                {
                    case TouchPhase.Began:
                    break;

                    case TouchPhase.Moved:
                        DragObject(deltaPosition);
                        break;

                    case TouchPhase.Ended:
                        break;
                }
            }

            //Debug.Log("target is " + touch.position + " pixels from the left");
        }

        void DragObject(Vector2 deltaPostion)
        {
            cashedTransform.position = new Vector3(Mathf.Clamp((deltaPosition.x * dragSpeed) + cashedTransform.position.x,
                startingPos.x - _horizontalimit, startingPos.x + _horizontalimit), 
            Mathf.Clamp((deltaPostion.y * dragSpeed) + cashedTransform.position.y,
            startingPos.y - _verticalLimit, startingPos.y + _verticalLimit),
            cashedTransform.position.z);

        }
    }

【问题讨论】:

  • 你能发布完整的错误吗?它应该告诉你哪条线路不工作......
  • 这里的问题是由于一个错字。有时你拼写它 POSITION,有时拼写为 POSTION。

标签: unity3d vector game-engine


【解决方案1】:

没有deltaPosition,因为您将变量命名为deltaPostion,因此错误('deltaPosition' does not exist in the current context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-28
    相关资源
    最近更新 更多