Gawd, I really hope someone on here can help me out here. I’m testing basics of physics - similar to a golf putting game.
The Scenario
I’ve got a default Unity scene, with a sphere and a terrain. The camera is in default position. The ball has the size and mass of a golf ball and all physics settings and friction etc are default. The ball has a rigid body and sphere collider.
I also have this bit of code attached to the ball…
Rigidbody rigidBody;
bool StartedShot;
Vector3 shotStart;
Vector3 shotEnd;
Vector3 direction;
float distance;
float forceAdjust = 0.05f;
void Start ()
{
rigidBody = this.GetComponent<Rigidbody> ();
StartedShot = false;
}
void Update ()
{
if (Input.GetMouseButtonUp(1))
{
rigidBody.velocity = Vector3.zero;
this.transform.position = Vector3.zero;
StartedShot = false;
}
// Starting shot
if (!StartedShot && Input.GetMouseButtonDown (0))
{
StartedShot = true;
shotStart = Input.mousePosition;
}
// Ending shot
if (StartedShot && Input.GetMouseButtonUp (0))
{
shotEnd = Input.mousePosition;
direction = shotEnd - shotStart;
float distance = direction.magnitude;
StartedShot = false;
Vector3 shootDirection = new Vector3(direction.x, 0.0f, direction.y);
rigidBody.AddForce(shootDirection * rigidBody.mass * forceAdjust, ForceMode.Impulse);
}
}
Now, when I run this - I can click and drag the mouse to apply a force on the ball. And although the ball does appear to go in the right direction, when you fire it in any other direction than left - it jumps (sometimes really high). If you fire it left, it ‘rolls’ more like I’d expect on a flat surface.
I’m guessing this has something to do with the lack of translation from the camera position to pushing the golf ball. I’m a bit confused by how the world space coordinates relate to the screen coordinates.
So how can I fire this ball based on the drag direction on screen, without the ball jumping to all directions other than left. How do I correctly translate the mouse input vectors to firing the ball in the right direction?
Thank you kindly in advance,
JM