Hi guys so I made a unity script to sort of cannonball launch a projectile, but i ran into a problem as the cannon ball only moves up and down (y-axis) and doesn’t move at all on the x-axis which eventually leads to a NAN error cuz of the math being used. What can I change in my script to make it work? (I call JumpAttack in a random if statement just to test it for now so dw abt that cuz it’s working)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IDK : MonoBehaviour
{
[SerializeField]
private Transform target;
[SerializeField]
private float initialAngle;
private Rigidbody2D rb;
private Vector2 p;
private float gravity = -9.8f;
private float angle;
private GameObject player;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
rb = GetComponent<Rigidbody2D>();
p = target.position;
angle = initialAngle * Mathf.Deg2Rad;
}
void JumpAttack()
{
Vector2 planarTarget = new Vector2 (p.x, 0);
Debug.Log("1");
Vector2 planarPosition = new Vector2 (transform.position.x, 0);
Debug.Log("2");
float yOffset = transform.position.y - p.y;
Debug.Log("3");
float distance = Vector2.Distance(planarTarget, planarPosition);
Debug.Log("4");
float initialVelocity = (1 / Mathf.Cos(angle)) * Mathf.Sqrt((0.5f * gravity * Mathf.Pow(distance, 2)) / (distance * Mathf.Tan(angle) + yOffset));
Debug.Log("5");
Vector2 velocity = new Vector2(initialVelocity * Mathf.Cos(angle), initialVelocity * Mathf.Sin(angle));
Debug.Log("6");
float angleBetweenObjects = Vector2.SignedAngle(Vector2.zero, planarTarget - planarPosition) * (p.x > transform.position.x ? 1 : -1);
Debug.Log("7");
Vector2 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector2.up) * velocity;
Debug.Log("8");
// Here is the actual movement
rb.velocity = finalVelocity;
Debug.Log("9");
}
}