【发布时间】:2020-05-27 05:40:12
【问题描述】:
我对编程和所有东西都是新手。我在 youtube 上观看了如何创建蛇游戏,我想为我的按钮添加一个脚本来移动播放器。我创建了ui buttons like this,但是当我点击它们时,当然没有任何反应。我为跨平台添加了简单的资产,所有这些都完成了,但我不知道如何编写脚本。我可以用我的W A S D 键移动蛇,但我想用 UI 按钮移动。这是我的脚本:
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
}
}
}
}
}
【问题讨论】: