For example, if i drag an object with mouse,when i throw it to the sky,the object will have a x-axis speed and a gravity,so the object will drop off very elegant and nice,but i can’t work it out.It make me very anxiety.Thanks anyway~
Do not worry, sit back, have a valium (if needed) and attach this script to the thrown object:
#pragma strict
/* Mouse Throw Physics by save
Attach this script to a GameObject you would like to throw
Last modified 2012-03-12
*/
@script RequireComponent(Rigidbody)
@script RequireComponent(Collider)
var strength : int = 20; //The strength to multiply in AddForce
var AlterUseOfGravity : boolean = true; //If useGravity is off and AlterUseOfGravity is off the object will continue to float
static var cam : Camera;
static var cameraTransform : Transform;
private var myTransform : Transform;
private var myRigidbody : Rigidbody;
private var myMagnitude : Vector3 = Vector3.zero;
private var initialPosition : Vector3;
private var setZdepth : float = .0;
private var activated : boolean = false;
function Awake () {
if (cam==null || cameraTransform==null) {
cam = Camera.main;
cameraTransform = cam.transform;
}
}
function Start () {
myTransform = transform;
myRigidbody = rigidbody;
initialPosition = myTransform.position;
}
function Update () {
if (activated) {
SetPosition();
}
}
function SetPosition () {
if (!myRigidbody.isKinematic) {
myRigidbody.isKinematic = true;
if (AlterUseOfGravity) myRigidbody.useGravity = false;
setZdepth = myTransform.position.z-cameraTransform.position.z;
}
var pos : Vector3;
pos = Input.mousePosition;
pos.x = Mathf.Clamp(pos.x, 0, Screen.width);
pos.y = Mathf.Clamp(pos.y, 0, Screen.height);
var newPos : Vector3 = Camera.main.ScreenToWorldPoint(Vector3(pos.x, pos.y, setZdepth));
myTransform.position = newPos;
myMagnitude = (myTransform.position - initialPosition) /Time.deltaTime;
initialPosition = myTransform.position;
if (Input.GetMouseButtonUp(0)) {
AddForce(myMagnitude);
}
}
function OnMouseDown () {
activated = true;
}
function AddForce (m : Vector3) {
myRigidbody.isKinematic = false;
if (AlterUseOfGravity) myRigidbody.useGravity = true;
myRigidbody.AddForce(m*strength);
activated = false;
}