- Home /
help me blow my balloon....
I am trying to create a prototype of a balloon that can me affected on a 2D plane by the users mouse clicks. Depending on the location i want to fire an AddForce function to push the balloon AWAY from the users click. here's what i'm trying to work with...
if (Input.GetButtonDown ("Fire1")) { // Construct a ray from the current mouse coordinates var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var objVect: Vector3;
var mouseVect: Vector3;
mouseVect[0] = (Input.mousePosition.x);
mouseVect[1] = (Input.mousePosition.y);
mouseVect[2] = (0);
print ("mouseVect is " + mouseVect);
objVect[0] = (myRigidBody.position.x);
objVect[1] = (myRigidBody.position.y);
objVect[2] = (0);
if (Physics.Raycast (mouseVect, objVect))
var forceX;
var forceY;
var multiplyer = .05;
forceX = ((Input.mousePosition.x) - (myRigidBody.position.x)) * multiplyer;
forceY = ((Input.mousePosition.y) - (myRigidBody.position.y)) * multiplyer;
//print ("forceX is " + forceX);
//print ("forceY is " + forceY);
myRigidBody.AddForce (forceX, 0, 0);
myRigidBody.AddForce (0, forceY, 0);
}
}
I think the problem is that i want to use the AddForce(Physics.Ratcast(mouseVect, objVect)) as my force but don't know how that's done.
Any help would be AWESOME!!!
Answer by Flimgoblin · Mar 12, 2010 at 09:18 PM
Just replied on your forum post but as this is meant to be the place I'll reply here too:
OK, looking at the docs this function that andeeee mentioned before is what you need.
http://unity3d.com/support/documentation/ScriptReference/Camera.ScreenToWorldPoint.html
This effectively does the raycasting/collision with the plane for you (which is the long way around I was suggesting before).
However, you need to set a Z position for it (which was missing before) - this is the distance forward from the camera. In your case you want that to be the Z position of the balloon relative to the camera.
So:
public var pushForceMultiplier:float=100.0; // you'll want to tweak that
function Update(){
if(Input.GetMouseButtonDown(0)){
// left click
var camDist=rigidbody.position.z-Camera.main.transform.position.z;
var clickPoint=Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x,Input.mousePosition.y,camDist)); // screen click point on the same Z distance from the camera as your rigidbody
var vec=rigidbody.position-clickPoint; // the direction from clickPoint to the rigidbody
vec=vec.normalized;
rigidbody.AddForce(vec*pushForceMultiplier);
}
}
NB. This is written as a script you attach to the balloon, rather than something you set a variable on linking to it.