1
votes

Sorry for the noob question, I am still new to unity.

Currently, I'm creating a 2d game in unity in which I have a game object that should move on the x-axis following the x touch position in a smooth way to create a nice swipe mechanics (taking into account that the object is constantly being influenced by the gravity of the Rigidbody2d).

I already tried doing it with Vector3.MoveTowards(), Rigidbody2D.MovePosition(), and changing the velocity of the Rigidbody2D, but none of those created a smooth movement.

Vector3.MoveTowards():

transform.position = Vector3.MoveTowards(transform.position, new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, transform.position.y, transform.position.z), speed * Time.deltaTime);

Rigidbody2D.MovePosition():

rigidbody2D.MovePosition(new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, 
transform.position.y, transform.position.z));

Rigidbody2D.velocity

Vector3 mousePositionWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (mousePositionWorld.x < transform.position.x)
{
   rigidbody2D.velocity = new Vector2(-speed - -(speed * takeOff), 
   rigidbody2D.velocity.y)
}

else if (mousePositionWorld.x > transform.position.y)
{
   rigidbody2D.velocity = new Vector2(+speed - (speed * takeOff), 
   rigidbody2D.velocity.y);
}

Am I missing something or is there a better way to achieve this?

1

1 Answers

0
votes

I don't know what you mean by smooth, but i think that you can use Lerp function. Here is an example: https://www.youtube.com/watch?v=d6BPukJ5QkA is a short video.