代码之家  ›  专栏  ›  技术社区  ›  Kaz

拖动游戏对象

  •  1
  • Kaz  · 技术社区  · 7 年前

    我正在使用下面的脚本在固定区域内上/下和左/右拖动游戏对象,这在编辑器上效果很好,也适用于移动刷卡,但由于某些原因,我似乎无法使用速度变量来减慢速度。知道我怎么做吗?我希望能够控制物体被拖动的速度。

    using UnityEngine;
    using System.Collections;
    
    public class drag : MonoBehaviour {
    
    public float maxXValue = 9f;
    
    Vector3 dist;
    float posX;
    float posY;
    
    
    void OnMouseDown(){
        dist = Camera.main.WorldToScreenPoint(transform.position);
        posX = Input.mousePosition.x - dist.x;
        posY = Input.mousePosition.y - dist.y;
    }
    
    void OnMouseDrag(){
    
        Vector3 curPos = new Vector3(Input.mousePosition.x - posX, Input.mousePosition.y - posY, dist.z);  
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
    
        if (GameManager.instance.gameStart == false) {
            worldPos.x = Mathf.Clamp (worldPos.x, -5f, 5f);
            worldPos.y = Mathf.Clamp (worldPos.y, -13.2f, -13.2f);
        } else {
            worldPos.x = Mathf.Clamp (worldPos.x, -maxXValue, maxXValue);
            worldPos.y = Mathf.Clamp (worldPos.y, -17.2f, -13.2f);
        }
    
        transform.position = worldPos;
    }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   ZayedUpal    7 年前

    可以采用速度变量和Lerp变换。位置改变速度变量将改变拖动速度。 这样地:

    using UnityEngine;
    using System.Collections;
    
    public class drag : MonoBehaviour {
        public bool gameStart = false;
        public float maxXValue = 9f;
        public float speed = 1.0f;
        Vector3 dist;
        float posX;
        float posY;
    
    
        void OnMouseDown(){
            dist = Camera.main.WorldToScreenPoint(transform.position);
            posX = Input.mousePosition.x - dist.x;
            posY = Input.mousePosition.y - dist.y;
        }
    
        void OnMouseDrag(){
    
            Vector3 curPos = new Vector3(Input.mousePosition.x - posX, Input.mousePosition.y - posY, dist.z);  
            Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
    
            if (gameStart == false) {
                worldPos.x = Mathf.Clamp (worldPos.x, -5f, 5f);
                worldPos.y = Mathf.Clamp (worldPos.y, -13.2f, -13.2f);
            } else {
                worldPos.x = Mathf.Clamp (worldPos.x, -maxXValue, maxXValue);
                worldPos.y = Mathf.Clamp (worldPos.y, -17.2f, -13.2f);
            }
    
            //transform.position = worldPos;
            transform.position = Vector3.Lerp(transform.position,worldPos,speed*Time.deltaTime);
        }
    }