There are 5 possible positions for the game object on the X axis. Pressing A moves the game object to the next position to its left, when it reaches the last position in this direction the game object gets teleported to the other side of the screen the same way pacman would do. Same in reverse with Q.
Here the variable playerPos = 0 (I guess it’s kind of useless in this code but oh well)
How would you guys make this code better? I feel like it could be written in like a couple lines if I knew of a way to simply add a value to the position instead of changing completly the position on each press but I don’t have the knowledge to do that.
Maybe something like this
Added some comments to explain the thought process behind it
// first make the x values editable in the editor
// no need to hardcode the values in code , makes the code more adaptable
// the code should get the x values from here , using the "currentIndex"
[SerializeField]
private float[] allXValues;
// save the index of the most recent position
private int currentIndex;
void Start()
{
// optional : initialize the player to be a the center
currentIndex = allXValues.Length / 2;
transform.position = new Vector3(allXValues[currentIndex] , 0 , 0);
}
void Update()
{
// we accumulate the total change done by the input
int delta = 0;
if(Input.GetKeydown(KeyCode.A))
{
delta --;
}
if(Input.GetKeydown(KeyCode.D))
{
delta++;
}
// if delta is zero , it means either no button was pressed
// or both pressed at the same time (in this case they cancel)
if(delta == 0)
return;
// we move the index
currentIndex += delta;
// (note : the "%" operator is used to give the remainder of a division)
// here ,we get the rest of the division by the number of all x values possible
// this should "snap" us back to the left if we go too far to the right
currentIndex = currentIndex % allXValues.Length;
// this should "snap" us back to the right if we go too far to the left
if(currentIndex < 0)
{
currentIndex += allXValues.Length;
}
// at this point the index should be valid , so we just grab the x value and assign it
transform.position = new Vector3(allXValues[currentIndex] , 0 , 0 );
}