Hey Guys,
I’m trying to make a snake game. I created snake and a game background. Then, I tried to spawn random food to be eaten by snake. But foods respawn out of my gamebackground.
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);
}
}
Other Script :
public class GameHandler : MonoBehaviour {
private FoodHandler foodHandler;
private void Start() {
foodHandler = new FoodHandler(20, 20);
}
private void Update()
{
}
}