Я новичок в программировании и все такое.Я посмотрел на YouTube, как создать игру змея, и я хочу добавить скрипт для моих кнопок для перемещения игрока.Я создал кнопки пользовательского интерфейса, как это , но когда я нажимаю на них, ничего не происходит, конечно.Я добавил простые ресурсы для кроссплатформенности, и все, что сделано, но я не знаю, как его написать.Я могу перемещать змею с помощью клавиш W A S D
, но я хочу двигаться с помощью кнопок пользовательского интерфейса.Вот мой сценарий:
private void Update()
{
if (isGameOver)
{
if (Input.GetKeyDown(KeyCode.R) || Input.GetMouseButtonDown(0))
{
onStart.Invoke();
}
return;
}
GetInput();
if (isFirstInput)
{
SetPlayerDirection();
timer += Time.deltaTime;
if (timer > moveRate)
{
timer = 0;
curDirection = targetDirection;
MovePlayer();
}
}
else
{
if (up || down || left || right)
{
isFirstInput = true;
firstInput.Invoke();
}
}
}
void GetInput()
{
up = Input.GetButtonDown("Up");
down = Input.GetButtonDown("Down");
left = Input.GetButtonDown("Left");
right = Input.GetButtonDown("Right");
}
void SetPlayerDirection()
{
if (up)
{
SetDirection(Direction.up);
}
else if (down)
{
SetDirection(Direction.down);
}
else if (left)
{
SetDirection(Direction.left);
}
else if (right)
{
SetDirection(Direction.right);
}
}
void SetDirection(Direction d)
{
if (!isOpposite(d))
{
targetDirection = d;
}
}
void MovePlayer()
{
int x = 0;
int y = 0;
switch (curDirection)
{
case Direction.up:
y = 1;
break;
case Direction.down:
y = -1;
break;
case Direction.left:
x = -1;
break;
case Direction.right:
x = 1;
break;
}
Node targetNode = GetNode(playerNode.x + x, playerNode.y + y);
if (targetNode == null)
{
//Game Over
onGameOver.Invoke();
}
else
{
if (isTailNode(targetNode))
{
//GameOver
onGameOver.Invoke();
}
else
{
bool isScore = false;
if (targetNode == appleNode)
{
isScore = true;
}
Node previousNode = playerNode;
availbableNodes.Add(previousNode);
if (isScore)
{
tail.Add(CreateTailNode(previousNode.x, previousNode.y ,tailParent));
availbableNodes.Remove(previousNode);
}
MoveTail();
PlacePlayerObject(playerObj, targetNode.worldPosition);
playerNode = targetNode;
availbableNodes.Remove(playerNode);
if (isScore)
{
currentScore++;
if(currentScore >= highScore)
{
highScore = currentScore;
}
onScore.Invoke();
if (availbableNodes.Count > 0)
{
RandomlyPlaceApple();
}
else
{
//you won
}
}
}
}
}