Search code examples
c#unity-game-engine

How to reference the right and left sides of a gameobject


In my game I am making a object move back and forth on anouther object. My idea was to use move towards and set the target to the right of the object an after it hits make the target the left of the gameobject. But I was unable to figure out how to reference the right or left of a gameobject. Any ideas?


Solution

  • If you are using the moveTowards then when it gets to the point you don't really need to detect when you get to the end. The detect spot is just an empty gameobject as a child on the main object on its right side. When the main object flips the spot flips with it. This setup is having a graphic that faces right. So, when it flips the same graphic will now be facing left. The two points in the list cannot be children of the moving object otherwise they will move with it and then it will never reach its point.

    [SerializeField] List<Vector2> locations = new List<Vector2>();
    int locationIndex = 0;
    [SerializeField] Vector2 moveToLocation;
    [SerializeField] float moveToDistance;
    [SerializeField] float moveToSpeed;
    [SerializeField] bool facingRight = true;
    [SerializeField] LayerMask detectMask;
    [SerializeField] Transform detectSpot;
    [SerializeField] float detectRadius;
    
    private void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, moveToLocation, moveToSpeed * Time.deltaTime);
        Flip(moveToLocation.x - transform.position.x);
        if(Vector2.Distance(transform.position, moveToLocation) < 0.1f)
        {
            transform.position = moveToLocation;
            if (locationIndex == locations.Count) locationIndex = 0;
            else locationIndex++;
            moveToLocation = locations[locationIndex];
        }
        // if you still want to detect something use this
        if (Physics2D.OverlapCircle(detectSpot.position, detectRadius, detectMask))
        {
            // what every you want to do when it collides
        }
    }
    
    
    void Flip(float _direction)
    {
        if((_direction > 0 && !facingRight) || (_direction < 0 && facingRight))
        {
            transform.localScale = new Vector2(transform.localScale.x * -1, transform.localScale.y);
            facingRight = !facingRight;
        }
    }