I have a 360 degrees shooter object and a projectile to shoot. My projectile has a Rigidbody2D with zero gravity scale. I want it to bounce off of colliders when it gets hit, but when I instantiate it from my shooter I have to write the velocity value in update so it keeps going against the colliders when shot. I figured that I should assign it a velocity in start function, but then it only goes in one direction. How do I fix this?
If I understand your question correctly, then I believe you are creating a top-down shooter game similar to the classic Asteroids.
You will want to add a force to the
RigidBody2D of your projectile instead of directly modifying its velocity. Below is a function I have use in one of my 2D games that applies force to a projectile at the provided angle and magnitude. This code is attached to my
Projectile script. You feed it the angle in degrees at which you would like to launch the projectile (0 for right, 90 for up, 180 for left, 270 for down), and adjust magnitude to determine how fast the projectile is launched.
RigidBody2D rb2D = GetComponent<Rigidbody2D>();
/// Launches the ball at the given angle and magnitude.
/// <param name="angle"></param>
public void LaunchProjectile(float angle, float magnitude)
float newAngle = angle * Mathf.Deg2Rad;
Vector2 direction = new Vector2(Mathf.Cos(newAngle), Mathf.Sin(newAngle));
rb2D.AddForce(direction * magnitude, ForceMode2D.Impulse);
If you want to ensure that your projectile will bounce off of the colliders it hits, then create a new
PhysicsMaterial2D and give it a friction value of 0 and a bounciness value of 1. You can create a new material by right clicking in the project folder and selecting "Create > Physics Material 2D". Once you've created a new one, drag it into the
Material field of your
Collider2D components in the inspector. For example, if you have a ball that you want to bounce off of a wall, then you'll want to add this material to the
Material field of both the ball and the wall's