Wasn’t able to find a question related to this, sorry if it’s been asked a million times.
I have a GameObject that normally is controlled by Rigidbody physics that can be thrown, but before it is thrown it is moved around by code and Unity’s physics are temporarily ignored. The player can drag the object around the screen, and when they stop dragging the object I want to allow physics to take over.
When the object is let go, I take the previousPosition of the object and calculate direction and velocity off of it and from here I want to convert that into Force so I can use one of the ApplyForce functions to make the object move as if it were thrown. My throw function is below, am I on the right track with this?
Your script is on the right track: don’t apply a force, just set rigidbody.velocity to the velocity the object had when you released it. That’s physically correct: when you drag an object and release it, the object initially keeps its last velocity. You should keep track of the last position each frame, calculate the velocity and assign it to rigidbody.velocity when it’s released.
I don’t know how you’re dragging the object, but supposing it’s dragged with the mouse in a horizontal plane (perpendicular to the Y axis), the script could be like this:
Vector3 lastPos;
Vector3 curVel;
bool dragging = false;
Plane movePlane;
void OnMouseDown(){ // object is grabbed:
rigidbody.isKinematic = true; // disable physics
lastPos = transform.position; // initialize lastPos
dragging = true; // enter drag mode
// create a logical plane at the object position and perpendicular to Vector3.up:
movePlane = new Plane(Vector3.up, transform.position);
}
void Update(){
if (dragging){
// create a ray from the camera passing through the mouse pointer:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance = 0f; // this will hold the distance camera->clicked point
if (plane.Raycast(ray, out distance)){ // if position valid...
// move the object to the plane position:
transform.position = ray.GetPoint(distance);
}
// calculate curVel:
curVel = (transform.position - lastPos)/ Time.deltaTime;
lastPos = transform.position; // update lastPos
}
}
void OnMouseUp(){ // object is released:
rigidbody.isKinematic = false; // enable physics first!
rigidbody.velocity = curVel; // copy curVel to the rigidbody
dragging = false; // exit drag mode
}