Apoleytaa
Apoleytaa

Reputation: 97

Unity Random Game Objects are spawning out of bond

I'm trying to make a snake game. I created snake and background.

Then I tried to spawn random foods to be eaten by snake. But My foods are spawning out of the background bonds.

Code :

public class FoodHandler {

private Vector2Int foodPosition ;
private int width;
private int height;

public FoodHandler(int width, int height)
{
    this.width = width;
    this.height = height;

    SpawnFood();
    FunctionPeriodic.Create(SpawnFood, 1f);

}


private void SpawnFood()
{
    foodPosition = new Vector2Int(Random.Range(0, width), Random.Range(0, height));
    GameObject foodGameObject = new GameObject("Snake'sFood", typeof(SpriteRenderer));
    foodGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.i.foodSprite;
    foodGameObject.transform.position = new Vector3(foodPosition.x, foodPosition.y);
    
}

       }



public class GameHandler : MonoBehaviour {

private FoodHandler foodHandler;

private void Start() {

    foodHandler = new FoodHandler(20, 20);
}

private void Update()
{
   
    
}

}

That's the screenshot :

enter image description here

Upvotes: 1

Views: 88

Answers (1)

Pac0
Pac0

Reputation: 23174

I suspect your background is centered at the origin (0;0). It means it spans from (-width/2;-height/2) on bottom-left corner to (width/2; height/2) on top-right.

Hence, if you generate values between (0;0) and (width;height), then only the top right corner of background is covered, and food can go beyond this.

Two solutions:

A) Move you background so that its bottom left corner is 0;0

B) Generate food location in the correct range, by simply subtracing (width/2) and (height/2) on respective values.

Upvotes: 1

Related Questions