- Home /
Shoot ball according to spot mouse gets clicked
Hi there
I would like to achieve the following: I have a sphere (my ball) and I'd like to shoot the ball in the direction according to where the mouse is clicked on the ball. I would just like to put the velocity as the vector3 between the mouse position and the centre of the ball. I just can't find how to correctly get this vector3 between the ball's centre and the mouse position.
I hope you guys can help!
Thanks in advance.
Answer by robertbu · Oct 23, 2014 at 06:47 PM
You need to get the position on the ball that corresponds to the mouse position through raycasting. Then you can create a vector by subtracting that from the transform.position of the object. Note for this task, you can use the more efficient Collider.Raycast() instead of Physics.Raycast():
#pragma strict
public var forceAmount : float = 350.0;
function Update() {
if (Input.GetMouseButtonDown(0)) {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (collider.Raycast(ray, hit, Mathf.Infinity)) {
rigidbody.AddForce((transform.position - hit.point).normalized * forceAmount);
}
}
}
Thanks for your answer! I'm having some difficulties though trying it out. I do my Unity program$$anonymous$$g in C# and I don't entirely know how to transform this JavaScript to the right C# statements :s $$anonymous$$ainly the var hit : RayCastHit, I have no idea (with my basic JS knowledge) how it translates to C#.
Answer by Eliasvdb · Oct 23, 2014 at 08:02 PM
Robertbu gave the right answer, but since I am doing it the C# way I had to fiddle a bit with the code. So here's what I used, based on robertbu's solution:
void OnMouseUp() {
Ray screenToPointer = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if(collider.Raycast(screenToPointer, out hit, Mathf.Infinity)) {
Vector3 theVector = (transform.position - hit.point).normalized;
rigidbody.velocity = new Vector3(theVector.x*10, theVector.y*10, theVector.z*10);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613165805im_/https://answers.unity.com/themes/thub/images/avi.jpg)