I have tried to make a scene where the player character moves between three positions on the X axis (the three public GameObjects). We can call them Left, Middle and Right. The player should move from left to middle, middle to right, right to middle and middle to left. I have made the arrow keys the input for movement. I would like it so that if you want to go from left to right (or right to left) you have to push twice on the corresponding key. I now have it working on going from right, to middle, to left. When I go from left, to middle, to right the player doesn’t stop in the middle. He doesn’t need two inputs from the right key.
This boggles my mind because the code is the same. I don’t know what I’m doing wrong. Been sitting with this for hours now. Sorry about all the lefts and rights and middles. Hope you can understand what I mean.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement3 : MonoBehaviour {
public GameObject posLeft, posRight, posMiddle;
bool isMoving;
void Start ()
{
}
void Update ()
{
bool moveLeft = Input.GetKey("left");
bool moveRight = Input.GetKey("right");
if( moveLeft == true && isMoving == false)
{
bool left = true;
Move(left: left);
}
else if (moveRight == true && isMoving == false)
{
bool right = true;
Move(right: right);
}
if (moveRight == true | moveLeft == true)
isMoving = true;
else
isMoving = false;
}
private void Move(bool left = false, bool right = false)
{
GameObject player;
player = GameObject.FindGameObjectWithTag("Player");
if (left == true && player.transform.position == posMiddle.transform.position)
player.transform.position = posLeft.transform.position;
if (left == true && player.transform.position == posRight.transform.position)
player.transform.position = posMiddle.transform.position;
if (right == true && player.transform.position == posLeft.transform.position)
player.transform.position = posMiddle.transform.position;
if (right == true && player.transform.position == posMiddle.transform.position)
player.transform.position = posRight.transform.position;
}
}
3182401–242787–Movement3.cs (1.56 KB)