- Home /
Using MoveTowards on button click
Hi,
I am currently building my first game with unity and so far it has been great. It's a 2d game where the player move up, right, left and currently I had that working with transform.position but because it is not detecting collision I am searching for another solution that is gonna have the same effect but it will detect a collusion if something is in the way instead of just teleporting the player object.
I've come across MoveTowards which somehow doesn't like the button click function and it only moves a little when it's pressed.
That's the code :
void jumpCenter()
{
Rigidbody2D myRigidbody = GetComponent<Rigidbody2D>();
Vector3 test = myRigidbody.transform.position;
Vector2 aPosition1 = new Vector2(test.x,1.4f);
test.y +=1.4f;
transform.position = Vector2.MoveTowards(new Vector2(transform.position.x, transform.position.y), aPosition1, 3 * Time.deltaTime/2);
}
When I add the same code in update() it works but that's not the effect that I want.
Do you have any idea what I might be doing wrong?
Thanks in advance!
when you want to use use colliders you have to use the game engines physics way of moving things. the easiest way is updateing the velocity every frame or addforse for a one time thing. then it will stop at collisions: Velocity is same as Vector2 or 3 direction. subtract start point from end point and update your velocity. when you directly change the position, it jumps past the physics engine