I am trying to make an object move and ricochet of walls in 2d, but my problem is I don’t know how to get it to do that. If I need to use a rigidbody, that’s fine, if I need to use something else, that’s fine, but I NEED to get this to work. Although it is not much, here is my code:
public class BallController : MonoBehaviour
{
public float speed;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
transform.Translate(Vector3.up * Time.deltaTime * speed);
}
This code below works perfectly for me in a 3D topdown game I’m making. I commented out the changes I think you’ll need to make in order to get it to work in a 2D game. I followed this 1 tutorial to create this.
The public layer mask tells the projectile what it is allowed to bounce off of. Set this to the same layer(s) as the walls in your game.
public LayerMask collisionMask;
public float speed;
private void BounceProjectile()
{
Ray ray = new Ray(transform.position, transform.forward); //You might have to change this to transform.up instead of transform.forward for a 2D game
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Time.deltaTime * ProjectileSpeed + 0.1f, collisionMask))
{
//Vector2 reflectDir2D = Vector2.Reflect(ray.direction, hit.normal);
Vector3 reflectDir = Vector3.Reflect(ray.direction, hit.normal);
float rot = 90 - Mathf.Atan2(reflectDir.z, reflectDir.x) * Mathf.Rad2Deg; //I think this should be Mathf.Atan2(reflectDir2D.y, reflectDir.x) * Mathf.Rad2Deg; for 2D
transform.eulerAngles = new Vector3(0, rot, 0); //For 2D I think this should be maybe Vector3(0,0,rot)
}
}