I’m having trouble making my object automatically move from right to left when it collides with a wall or another object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class autoMove : MonoBehaviour
{
public float speed = 3.0f; // adjust the speed to your liking
private bool movingRight = true; // initial direction
private bool movingLeft = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (movingRight)
{
transform.Translate(Vector3.right * speed * Time.deltaTime);
}
else
{
transform.Translate(Vector3.left * speed * Time.deltaTime);
}
}
private void OnTriggerEnter2d(Collider2D other)
{
movingRight = false;
}
}
When it collided with a wall, it doesn’t move in the opposite direction. How do I fix this?