Currently making a Unity 2D game that includes rocket jumping (e.g TF2, Quake). I have successfully created the code that launches the player in the correct direction depending on the position of an explosion prefab (which is just a circle). I wish to implement a multiplier that changes the applied force depending on the player's distance from the explosion.
I've experimented with using Vector2.Distance but I have had no luck thinking of ways to convert this into a meaningful value.
Here's my current code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HandleExplosion : MonoBehaviour
{
[SerializeField] float launchSpeed;
[SerializeField] float explosionTime;
private void Start()
{
StartCoroutine(DeleteExplosion());
}
private void OnCollisionEnter2D(Collision2D player)
{
if (player.gameObject.CompareTag("Player"))
{
Debug.Log(CalculateForceMultiplier(player));
Vector2 launchPos = player.transform.position - transform.position;
player.gameObject.GetComponent<Rigidbody2D>().AddForce(launchPos * launchSpeed * CalculateForceMultiplier(player), ForceMode2D.Impulse);
}
}
float CalculateForceMultiplier(Collision2D player)
{
return Vector2.Distance(player.transform.position, transform.position);
}
IEnumerator DeleteExplosion() {
yield return new WaitForSeconds(explosionTime);
Destroy(gameObject);
}
}
float CalculateForceMultiplier(Collision2D)
{
Vector2 _dist = Vector2.Distance(player.transform.position, transform.position);
return _dist != 0 ? 1f / _dist : 100f;
}
In your code, the method returned the distance between the explosion and the player. By doing this, the farther away the player is, the larger the return value will be, and the closer it is, the smaller it will be, which I intuitively think is the opposite of what you want. In the method I wrote I check if the distance between the explosion and the player is different from 0 and if it is true I return 1 / the distance, i.e. the closer it is, the closer the returned value will be the greater, while the farther away the more the returned value will be close to 0. If the two objects are in the same position, trying to divide 1 / the distance, that is 0, you would get an exception, so if this happens I set a very large value to be returned because the power would ideally be maximum.