Kaz
Kaz

Reputation: 147

Dragging GameObject

I am using the script below to drag a game object up/down and left/right within a fixed areas and this works well on the editor and also for mobile swiping but for some reason I cannot seem to slow it down using a speed variable. Any idea how I can do this? I want to be able to control the speed at which the object can be dragged.

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;
}
}

Upvotes: 1

Views: 108

Answers (1)

ZayedUpal
ZayedUpal

Reputation: 1601

You can take a speed variable and Lerp transform.position. Changing the speed variable will change drag speed. Like this:

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);
    }
}

Upvotes: 1

Related Questions