Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Values not being implemented properly

I am trying to start coding in unity and I was following a tutorial. Long story short I wanted to edit the game after I finished the tutorial. I wanted to make it so a game object would randomly spawn in a different place after collecting. Here is the script for the object to be collected:

void Start()
{
    float x = Random.Range((float)-17.5, 17);
    float y = Random.Range((float)-8.6, (float)8.6);
    transform.Translate(x, y, 0);
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Rabbit")
    {
        score++;
        if (score >= winScore)
        {
            winText.SetActive(true);
        }
        else
        {
            float x = Random.Range((float)-17.5, 17);
            float y = Random.Range((float)-8.6, (float)8.6);
            transform.Translate(x, y, 0);
        }

    }
}

The code is supposed to move the object when it comes into contact with the controlled Rabbit object however the object sometimes moves outside the range parameters.

I tried thinking about moving this code out of the collision function but no matter how much I thought about it, I couldn't see where it would go for it to work. The object isn't in any parent objects as I had a small problem with coordinates being different when in a parent object so I am not sure why it is spawning outside its range. As an extra note I am still very new to unity so there may be some things that I am unaware of that could be affecting it but any fixes are welcome.

like image 883
Zach Vass Avatar asked May 17 '26 19:05

Zach Vass


1 Answers

transform.Translate(x, y, 0)

Moves the object starting from the current location!

You rather want to overwrite the world space absolute position

transform.position = new Vector3(x, y, 0);

or localPosition if it has to be not in world space but relative to a parent


In general Why do you use double and a cast

(float)-17.5

instead of simply float directly

17.5f

See Real literals


And then to make your code more flexible and better to maintain I would expose the ranges to the Inspector (=> you can adjust them without the need to recompile) and have a reusable method (don't repeat yourself)

[SerializedField] private Vector2 minPosition;
[SerializedField] private Vector2 maxPosition;

private void SetRandomPosition()
{
    var x = Random.Range(minPosition.x, maxPosition.x);
    var y = Random.Range(minPosition.y, maxPosition.y);
    
    transform.position = new Vector3(x, y, 0);
}
like image 118
derHugo Avatar answered May 20 '26 09:05

derHugo