- Home /
I need help with rigidbody2D/gravity stuff
Hi guys, hope you're well. Recently I tried to write a piece of code to teleport a floating character(rigidbody2D with gravity applied) to wherever clicked. However, as I tested, it turned out that each time the character's teleported, he fell a little faster than the last time(feels like gravity scale got higher). I don't know what caused this, so if possible, can anyone help me ?
Below is the teleportation code I wrote:
void Update () {
if (Input.GetMouseButtonDown(0)) {
GameObject player = GameObject.Find ("Player");
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
player.transform.position = mousePos;
}
}
Please share me your thoughts, thanks a lot in advance !
You should also grab the player in the Start() function.
void Start()
{
GameObject player = GameObject.Find("Player");
}
void Update ()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
player.rigidbody2D.velocity = new Vector2(0,0);
player.transform.position = mousePos;
}
}
Thank you very much, this line really did the trick !
player.rigidbody2D.velocity = new Vector2(0,0);
Glad it helped! Please mark the answer below as accepted so that other folks know this issues is answered.
Answer by MakeCodeNow · Feb 19, 2014 at 04:12 PM
You need to zero out the velocity whenever you teleport.
Your answer
Follow this Question
Related Questions
Rigidbody y velocity is stuck on 0, gravity is not turned off. 2 Answers
Rigidbody gravity between planets 1 Answer
Enable rigidbody gravity,Enable Rigid body gravity 3 Answers
Raycasting ray go through object with gravity enabled 0 Answers
Turret floats away and pushes everything away from it 2 Answers