I can't figure out how to properly add force so that the bullet will go to the cursor.
public class Shoot : MonoBehaviour
{
[Header("Bullet prefab")]
public Rigidbody2D Bullet;
public float power;
public Transform ts;
private Rigidbody2D newBullet;
public GameObject cross;
public GameObject spawner;
private Vector3 crossHair;
void CreateBullet(Vector3 dire)
{
if (Input.GetMouseButtonDown(0))
{
newBullet = Instantiate(Bullet, ts.position, Quaternion.identity) as Rigidbody2D;
newBullet.AddForce(dire * power, ForceMode2D.Impulse);//Problem here
}
}
//fix these not working as intended
//Almost the solution
private void Update()
{
crossHair = new Vector3(cross.transform.position.x, cross.transform.position.y, 0);
Ray ray = Camera.main.ScreenPointToRay(crossHair);
Vector3 direction = (ray.GetPoint(100000.0f) - spawner.transform.position).normalized;
CreateBullet(direction);
}
}
↧