Hi, I’m trying to try make projectiles that targets and launches at the player, and the player has to counter them.
The Projectiles has three heights: peak height, mid height and the ground height.
_
What I want to do is add deceleration to the math for horizontal velocity for peak height, making it go in an arc near the end instead of the middle while heading towards player in a correct spot and not over or under shooting.
_
Here is the picture to show how I want the projectile to move, it may not be accurate but it should give a general idea.
I took most of the math from this video:
- The math is about kinematics, here are the equations it uses: 1. s = ((u + v) * t) / 2
2. v = u + a * t
3. s = u * t + (a * t * t) / 2
4. s = v * t - (a * t * t) / 2
5. v * v = u * u + 2 * a * s
v = final velocity
u = initial velocity
a = acceleration (gravity)
s = displacement
t = duration time
_
Here is the code for the launch function for your perusal.
public float deceleration = 5f;
public float jumpHeight = 2f;
[SerializeField] private bool launchAtAwake;
[SerializeField] private Transform target;
Vector3 LaunchVelocity(Vector2 targetPosition, float heightTarget)
{
float displacementY = heightTarget - rb.heightPosition;
Vector3 displacementXZ = new Vector3(targetPosition.x - rb.groundPosition.x, 0f,
targetPosition.y - rb.groundPosition.y);
float time = Mathf.Sqrt(-2f * jumpHeight / -rb.gravity) +
Mathf.Sqrt(2f * (displacementY - jumpHeight) / -rb.gravity);
Vector3 velocityY = Vector3.up * Mathf.Sqrt(-2f * -rb.gravity * jumpHeight);
// The original Code for horizontal velocity
//Vector3 velocityXZ = displacementXZ / time;
// One of my Attempts for horizontal velocity with deceleration
Vector3 velocityXZ = new Vector3(
Mathf.Sqrt(-2f * -deceleration * Mathf.Abs(displacementXZ.x)), 0f,
Mathf.Sqrt(-2f * -deceleration * Mathf.Abs(displacementXZ.z)));
return velocityXZ + velocityY;
}
_
This is the code for deceleration.
private Vector2 facingVelocity;
void FixedUpdate()
{
float moveSignX = movementSpeed.x != 0f ? Mathf.Sign(movementSpeed.x) : 0f;
float moveSignY = movementSpeed.y != 0f ? Mathf.Sign(movementSpeed.y) : 0f;
rb.groundPosition += new Vector2(moveSignX * facingVelocity.x,
moveSignY * facingVelocity.y) * Time.deltaTime;
if (deceleration > 0)
Accelerate(-deceleration);
}
void Accelerate(float accel)
{
float facingVelX = Mathf.Clamp(facingVelocity.x + accel * Time.deltaTime, 0f, Mathf.Infinity);
float facingVelY = Mathf.Clamp(facingVelocity.y + accel * Time.deltaTime, 0f, Mathf.Infinity);
facingVelocity = new Vector2(facingVelX, facingVelY);
}
_
I’m having a hard time trying to get this problem to work so I’m asking anyone, especially who knows kinematic better then I do, if they know how to solve this math problem.
Thank you.
