- Home /
Make something move away from click point.
Goal:
Trying click on a point and have a ball bounce away from that point. I am trying to do this in 2D so I have it ignoring the z component on the rigid body.
My Solution?
I think what I want to do is take the position of the ball (x,y), subtract the position of the mouse click (x,y) and use that to create a new vector to give the rigidbody as a force.
So Far:
I was able to get the position of the click into a Vector3. I am not sure how to get the position of the ball into a Vector3. I don't know how to subtract the two, and if thats even the right idea. I know how to give it a push in a direction using AddRelativeForce.
I was afraid to ask because I feel like I should understand more before attempting to get help.
How could you do this in a 2D context? If you wanted your ball to move away from the clicked point, that would entail movement in 3D axes! I'm not sure I understand how you want the ball to be repelled from the screen point if you are only using 2D axes ...
unless, of course, you mean 2.5D. In which case, it's entirely possible. :)
I think a bit of clarification is needed ... for me at least.
Answer by stevenp · Mar 13, 2012 at 09:16 AM
To get the ball position:
private var xPos:float;
private var yPos:float;
xPos = ballObject.position.x;
yPos = ballObject.position.y;
Then you get the distance between your mouse click and ball position, see from here.
You can just use the distance to determine how powerful the force will be.
Answer by glipzcom · Mar 13, 2012 at 06:09 PM
Thanks guys. I kept hacking at it and this is what I came up with. I am working in 3D but I am doing all resulting motion in 2D.
ballPoint = this.transform.position;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
clickPoint = ray.GetPoint (10) ;
clickPoint.z = 0;
Vector3 newVector = ballPoint - clickPoint;
newVector.Normalize();
rigidbody.AddForce(newVector*20,ForceMode.Impulse);
The part that was screwing me up, and I am still not entirely sure how it "works" is subtracting one vector from another, and then normalizing. But my ball now flys away from my mouse on click, so its started.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Unable to fully rotate GameObject on tap 2 Answers
How to compute the change in vector when it's referential vector changes? 0 Answers
Instantiating at Collision Point. 2 Answers
A fast triangle triangle intersection algorithm for unity? 4 Answers