- Home /
Moving 2D Game Object on GUI Button Click
Hey guys, I need to move an object to the left when a button is clicked, changing the scene when it goes past a certain point. I want it to move steadily in a direction though instead of teleporting like it is now. Currently when I push the button my 2D player sprite just moves a few units to the right
void OnMouseDown(){
Debug.Log("Pushed");
if(currMenu == menuState.title)
{
currMenu = menuState.weapon;
}
else if(currMenu == menuState.weapon){
objToMove.rigidbody2D.AddForce(Vector3.right * 3000);
if (objToMove.transform.position.x > 15){
Application.LoadLevel("Level1");
}
}
}
How odd. AddForce is not a teleport sort of movement. Perhaps something else is preventing your object from continuing to move. Offhand, I would guess there's an animation with apply root motion enabled?
Answer by MikeNewall · May 13, 2014 at 11:21 PM
OnMouseDown is only called once when you click. Use OnMouseOver which is called while your mouse is over the button. You can then check if the left mouse button is down and if so move your object. Something like this:
void OnMouseOver(){
if(Input.GetMouseButton(0)){
// move the player
}
}
Ok guys, I did it by implementing $$anonymous$$ike's suggestion in addition to adding a downward force so the object moves to the side and towards the center of the screen. Thanks!
Answer by AdvsNoob · May 13, 2014 at 11:42 PM
OnMouseOver will resolve this issue for you, Mike is correct.
void OnMouseOver(){
if(Input.GetMouseButton(0)){
if(currMenu == menuState.title)
{
currMenu = menuState.weapon;
}
else if(currMenu == menuState.weapon){
objToMove.rigidbody2D.AddForce(Vector3.right * 3000);
if (objToMove.transform.position.x > 15){
Application.LoadLevel("Level1");
}
}
}
}