I’m currently working on a personal project and I need a rocket jump to work. I’m having trouble in that I can’t get the rocket jump to send my player in a diagonal or sideways direction, it only sends them upwards. Here’s the code that controls how the explosions work:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket : MonoBehaviour
{
[SerializeField] private float rocketTime;
[SerializeField] private float explosionRadius;
[SerializeField] private float explosionForce;
private void Start()
{
// Destroy the rocket after a set time if it doesn't collide
Destroy(gameObject, rocketTime);
}
private void OnCollisionEnter2D(Collision2D collision)
{
// Apply explosion logic and destroy the rocket
ApplyExplosion();
Destroy(gameObject);
}
private void ApplyExplosion()
{
// Check for collision with the player within the explosion radius
Collider2D playerCollider = Physics2D.OverlapCircle(transform.position, explosionRadius, LayerMask.GetMask("Player"));
if (playerCollider != null && playerCollider.CompareTag("Player"))
{
Rigidbody2D rb = playerCollider.GetComponent<Rigidbody2D>();
PlayerMovement playerMovement = playerCollider.GetComponent<PlayerMovement>();
if (rb != null && playerMovement != null)
{
// Calculate the direction from the explosion to the player
Vector2 direction = playerCollider.transform.position - transform.position;
// Calculate the distance between the explosion and the player
float distance = direction.magnitude;
// Apply force based on the square root of the distance (multiplied by a constant)
float force = Mathf.Sqrt(distance) * explosionForce;
// Normalize the direction and apply the force
direction.Normalize();
rb.AddForce(direction * force, ForceMode2D.Impulse);
// Set isRocketJumping to true if the player is in the air
if (!playerMovement.IsGrounded)
{
playerMovement.SetRocketJumping(true);
}
}
}
}
private void OnDrawGizmosSelected()
{
// Visualize the explosion radius in the editor
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, explosionRadius);
}
}