- Home /
AddForce at mouse position only on table area
I have a very specific question - First of all I am able to rotate stick around the ball according to the mouse position so this is working perfectly fine.
Now I need to add the force at the direction of cursor position within the surface of table only. so If I just click on the green area for example pointing to yellow ball and press mouse down or any where then it should move the ball there - Right now its only adding the force at the direction of x,y but z is always coming as 0.
here is the code as Force Script.
void OnMouseDown()
{
Debug.Log("OnMouseDown in the table");
Vector3 mouse_pos = Input.mousePosition;
//transform is my Table Area.
Vector3 object_pos=Camera.main.WorldToScreenPoint(this.transform.position);
mouse_pos.x = mouse_pos.x - object_pos.x;
mouse_pos.y = mouse_pos.y - object_pos.y;
//This is the problem where z of mouse_pos always 0.0 in Debug.Log
//Que_Ball.rigidbody.AddRelativeForce(mouse_pos,ForceMode.Force);
Que_Ball.rigidbody.AddForce(mouse_pos);
}
So what is happening now? Typically I would do these kinds of calculations by converting the mouse/screen coordinates into world coordinates rather than convert world coordinates into screen coordinates. But I what you have here should work, or should work if you get the amount of force correct. That is:
Que_Ball.rigidbody.AddForce(mouse_pos.normalized * amount);
So you have a 2D surface. Why do you want any force applied in the 'Z' direction? A few seconds of video so see what is going on would be helpful.
I have a Top Camera - so only x and z coordinates will work for the direction on the table - So I am basically moving my mouse in x and z coordinates from top Camera.
I am trying your solution and see if that works then let you know.
Try this:
Vector3 v3 = new Vector3(mouse_pos.x, 0.0, mouse_pos.y);
Que_Ball.rigidbody.AddForce(v3.normalized * amount);
Its still not working - still moving in x direction where I need it to move in the angular direction - I have tried with Force$$anonymous$$ode.Impluse as well but still not working as desired.
Try doing a Debug.Log(mouse_pos). You want to verify that the x and y position make sense with respect to the indicator. With this last change, you should be getting both X and Z components to the AddForce().