Cristiano Santos
Cristiano Santos

Reputation: 2137

Accelerate and decelerate to finger position

I have a 3D object on Unity and what I want is simply move this object as soon as the user presses the screen. The problem is that it needs to accelerate first and then, when it is reaching the pressed position, it starts decelerating until it totally stops on that point.

I need this to work in a way that if the user moves his finger, the object will recalculate if it needs to accelerate/decelerate based on his current condition.

I tried this example but, it only works for acceleration and it also seems a little confusing. So, I was thinking if someone else have a better and simple idea to solve this. Can physics help with this? If so, how?

My code is in C#.

Upvotes: 0

Views: 1106

Answers (1)

Verv
Verv

Reputation: 765

Using unity rigidbody system and simple calculate. This is using mouse position, you can change it to touch.

public class MyDragMove : MonoBehaviour {
    public float speedDelta = 1.0f;
    public float decelerate = 1.0f;
    private bool startDrag;
    private Vector3 prePos;

    void Update () {
        this.rigidbody.drag = decelerate; //Rigidbody system can set drag also. You can use it and remove this line.

        if (Input.GetKeyDown (KeyCode.Mouse0)) {
            prePos = Input.mousePosition;
            startDrag = true;
        }
        if(Input.GetKeyUp(KeyCode.Mouse0))
            startDrag = false;

        if(startDrag)
            ForceCalculate();
    }

    void ForceCalculate()
    {
        Vector3 curPos = Input.mousePosition;
        Vector3 dir = curPos - prePos;
        float dist = dir.magnitude;
        float v = dist / Time.deltaTime;

        this.rigidbody.AddForce (dir.normalized * v * Time.deltaTime * speedDelta);
        prePos = curPos;
    }
}

or just use SmoothDamp toward last position.

public class MyDragMove : MonoBehaviour {
    public float speedDelta = 1.0f;
    public float maxSpeed = 5.0f;
    public Vector3 v;
    private Vector3 prePos;

    void Update () {
        if(Input.GetKey(KeyCode.Mouse0))
            prePos = Input.mousePosition;

        TowardTarget ();
    }

    void TowardTarget()
    {
        Vector3 targetPos = Camera.main.ScreenToWorldPoint (new Vector3(prePos.x, prePos.y, 10f)); //Assume your camera's z is -10 and cube's z is 0
        transform.position = Vector3.SmoothDamp (transform.position, targetPos, ref v, speedDelta, maxSpeed);
    }
}

Upvotes: 2

Related Questions