Hi @CoolCosmos .
Your post was really helpfull but I have a problem with the transform.forward ( or I don’t understand the functionnality). If I use your code the bullet will not move because transform.forward is always equal to (0,0,1). I don’t know if the problem is on the instantiate but there is my code:
When the player shoot:
private void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab,firePoint.position,transform.rotation);
}
The actual bullet script :
public class Bullet : MonoBehaviour
{
private Rigidbody2D rb;
public float thrust = 20;
private Vector3 direction;
void Start()
{
rb = GetComponent<Rigidbody2D>();
direction = transform.forward;
}
void Update()
{
rb.velocity = direction * thrust;
}
private void OnCollisionEnter2D(Collision2D collision)
{
ContactPoint2D contact = collision.GetContact(0);
if (collision.gameObject.tag == "Wall")
{
direction = Vector3.Reflect(direction, contact.normal);
}
}
}
Edit: If I put
direction = transform.up;
instead of transform.forward (on the start method), the bullet will reflect well but the bullet does not rotate in the direction it is going
I keep shearching. Thank you to take time to help beginners
Antoop1
Edit: Nevermind, I found a solution.
I use the vector “direction” to find a angle and apply it to the bullet:
in the update method :
float rotationz = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotationz - 90);
Like I said before, in the start method i used transform.up instead of transform.forward.
Here is the working code:
void Start()
{
rb = GetComponent<Rigidbody2D>();
direction = transform.up;
}
// Update is called once per frame
void Update()
{
rb.velocity = direction * thrust;
float rotationz = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotationz - 90);
}
private void OnCollisionEnter2D(Collision2D collision)
{
ContactPoint2D contact = collision.GetContact(0);
if (collision.gameObject.tag == "Wall")
{
direction = Vector3.Reflect(direction, contact.normal);
}
}
}
Thank you for your really helpfull answers.
Antoop1