move object to fixed position (from .x 20 to .x 40) on swipe
I want to move my object a fixed amount to the right/left (on x axis) on swipe. I have my functions to detect swipe, but I don't know a good way to move my object.
This is what I've got so far
public float speed;
private Rigidbody2D rb2d;
void Start(){
rb2d = GetComponent<Rigidbody2D>();
}
// leaving out swipe detection method, not relevant
public void onLeftSwipe () {
Vector2 movement = new Vector2(rb2d.position.x -20, rb2d.position.y);
rb2d.AddForce(movement * speed);
}
This will add a force to my object, but what I need is to make the object stop when it has reached its destination, which is current position - 20, on left swipe. I don't want to just give it a new position, I must have that feeling of the object traveling there.
I am very new to unity, and c#, so it would be better to give me advice on how to solve it (pointing me to tutorials, docs, examples) rather than providing the solution, if you do have a good solution to share, please explain it also :)
Answer by LeslieCrooks · Jun 26, 2018 at 08:38 AM
Hello! I'm sure you've already found an answer by now, but for anyone else wondering how to do something like this, the Vector3.MoveTowards command does what is described in the above scenario, Documentation here:
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html