- Home /
Reset position for rigidbody2d
I trying to learn Unity and make volleyball game like Arcade Volleball. After each round I reset position of each player to its start position by calling ResetPosition method.
public class BaseController : MonoBehaviour
{
private Vector3 spawnPoint;
private void Start()
{
spawnPoint = transform.position;
}
public void ResetPosition()
{
rigidbody2D.velocity = Vector2.zero;
transform.position = spawnPoint;
}
...
}
Everything works fine, but do not leave me thinking that I did something wrong. I have 2 questions:
1) Is it normal than I change position directly? Because I don't know how to change it in another way.
2) So does it mean than there is no overheap in performance of physic engine if I change position for object with collider but without rigidbody?
Answer by Linus · Feb 26, 2014 at 11:24 AM
Rigidbody2D does have IsKinematic checkbox.
There is not problem doing what you are doing. Even if it was a costly performance I would not matter when done once in a while. Problem is if doing in every frame. That goes for about any thing related to micro optimization.
Thanks for answer. What you can say about in-game object's position change by changing it's rigidbody.velocity? I saw it in official Unity tutorial http://www.youtube.com/watch?v=Xnyb2f6Qqzg For exmaple, rigidbody.velocity = new Vector2(Input.GetAxis("Horizontal) Speed, 0); But in official 2D Unity project https://www.assetstore.unity3d.com/#/content/11228 everywhere using technic of rigidbody2D.AddForce(Vector2.right Input.GetAxis("Horizontal)); Which option is more correct or they are both viable?
@leto: you are free to modify anything you like. Either use AddForce, which means the physics engine will adjust the velocity by itself, depending on the Rigidbody's mass and the force's dircetion and so on. Or change the velocity directly, skipping physics computations (for example, ignoring the mass). Or directly set the position, making the object teleport. The physics engine is fine with all of this.
velocity is the current movement to be applied by the physics engine.
rigidbody2D.velocity is a Vector2. X and Y. You only want to use Y, and gravity takes care of that for you.
When it collides with things it gains velocity on x, sideways.
In a script on your spike, have:
I usually write in UnityScript, should be trivial to convert. You might consider making a reference to the rigidbody2d component.
function FixedUpdate(){
//Resets sideways movement to 0
rigidbody2D.velocity.x = 0;
}