- Home /
How to move a GameObject around with physics
Hello I have a gameobject that has a Rigidbody2D on it & im also able to move my gameobject around with mouse & touch
private Vector3 offset;
void Update ()
{
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
}
void onMouseDrag()
{
Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
transform.position = Camera.main.ScreenToWorldPoint(newPosition) + offset;
}
but I want to be able to basically throw the game object around the screen (2D) but when I let go of the gameobject it just falls cause gravity is at 1
Answer by jandd661 · Sep 19, 2018 at 01:29 AM
Start here:
https://unity3d.com/learn/tutorials/topics/2d-game-creation/rigidbody-2d
Then go here:
https://docs.unity3d.com/Manual/class-Rigidbody2D.html https://docs.unity3d.com/ScriptReference/Rigidbody2D.html
Answer by CherryPicker · Sep 19, 2018 at 10:43 AM
My guess would be to measure the distance between when you click and when you let off the mouse and divide by time to get force.
So in pseudo-code it would be something like this
float timeHolding;
Vector2 startPosition;
Vector2 endPosition;
float forceToAdd;
onClick()
{
Time.StartCounting();
startPosition = yourObject.transform.position;
}
onMouseOff()
{
timeHolding = Time.StopCounting() [get the time spent while holding]
Vector2 endPosition = yourObject.transform.position;
forceToAdd =((endPosition.x - startPosition.x) + (endPosition.y - startPosition.y)) / time;
yourObject.RigidBody2D.addForce
(new Vector2(endPosition.x - startPosition.x, endPosition.y - startPosition.y), forceToAdd);
}
Or something like that I imagine.