- Home /
Moving the player in a ballistic trajectory in 3D
Hi! I'm currently struggling with this issue for about two weeks and can't seem to get the hang of it.
Here's the premise: I want to create a 3D platformer where one of the player's abilities is to "slingshot" around the levels. Think Angry Birds, but in 3D.
I've currently managed to get a system working where the player can visualize the trajectory arc and control its velocity (a float) and angle (). What I want to do next is: after a certain button is pressed, the game takes the velocity and angle provided and moves the player object along that trajectory.
The problem I'm having is that the player object either doesn't move at all, or is thrown into the distance at great speed. I've tried both the rigidbody.AddForce method and modifying the player's rigidbody velocity directly.
I originally figured that if I calculate the velocity vector and use that as the force, it would work, but it didn't.
From my projectile arc generator, I can get the angle, velocity (float) and target position of the trajectory.
Here's the code for the trajectory movement & velocity: Note: the Slingshot1 function is simply called in Update (for testing purposes).
private void Slingshot1()
{
if (inputJump)
{
slingVelocity = CalculateAngularVelocity(transform.position, aMesh.GetTargetPosition(), aMesh.GetAngle());
rb.AddForce(slingVelocity, ForceMode.VelocityChange);
//StartCoroutine(SlingshotTimer());
}
}
private Vector3 CalculateAngularVelocity(Vector3 start, Vector3 target, float angle)
{
Vector3 direction = target - start;
float h = direction.y;
direction.y = 0.0f;
float distance = direction.magnitude;
float a = angle * Mathf.Deg2Rad;
direction.y = distance * Mathf.Tan(a);
distance += h / Mathf.Tan(a);
//Velocity calc
float velocity = Mathf.Sqrt(distance * Physics.gravity.magnitude / Mathf.Sin(2 * a));
return velocity * direction.normalized;
}
Thank you for taking some time for looking into this issue!