add force to direction

so what I have is a script that calculates the angle from the player to the mouse. It works just fine. Right is 0/360, up is 90, left is 180, down is 270.

I wanted to take that angle and use it with addforce to sort of make the character jump at the mouse… Nothing seems to be working.

v3Pos = Input.mousePosition;
v3Pos.z = (playerObject.transform.position.z - cameraObject.transform.position.z);
v3Pos = cameraObject.ScreenToWorldPoint(v3Pos);
v3Pos = v3Pos - playerObject.transform.position;
jumpRotation = Mathf.Atan2 (v3Pos.y, v3Pos.x) * Mathf.Rad2Deg;

if (Input.GetMouseButtonUp(0))
{
playerObject.AddForce(dir * force);;
}

I’m returning an error:
Assets/PlayerMover.js(21,30): BCE0023: No appropriate version of ‘UnityEngine.Rigidbody.AddForce’ for the argument list ‘(int)’ was found.

Please help.

What are the types of dir and force? I suppose the error is in the if statement (line 21 in your full file)?

3 Answers

3

Actually you don’t need the angle at all. Just do:

playerObject.AddForce(v3Pos * factor);

or

playerObject.AddForce(v3Pos.normalized * factor);

‘factor’ will be a variable you declare and likely need a value of in the range of 200 - 1500. The first line of code will result in more force being added if the object is further away. The second suggested line will add the same amount of force no matter the distance.

Functions exactly as intended and is a much simpler solution. Props.

playerObject is a gameObject. It needs to be a RigidBody value type to use AddForce

the gameObject has a rigidbody component

I figured you had to use playerObject.rigidbody.AddForce. I wasn't aware that you could use AddForce directly on the gameObject reference.

i just use this :
rb.AddForce(transform.TransformDirection(Vector3.back).normalized * forceValue, ForceMode.VelocityChange);

and the directions using Vector3.back (forward, left, right)