- Home /
3D Endless Runner - Click/Tap to move
Hi. So I'm trying to make a 3d Endless Runner and I've got a script for switching lanes whenever you press A or D. But what I want is to make it work on mobile, so I need the script to detect when you click on the left side of the screen, or the right side. Swiping left/right would be even better.
Here's the script that I've got for switching lanes:
float input = Input.GetAxis("Horizontal");
if(Mathf.Abs(input) > deadZone) {
if(!didChangeLastFrame) {
didChangeLastFrame = true; //Prevent overshooting lanes
laneNumber += Mathf.RoundToInt(Mathf.Sign(input));
if(laneNumber < 0) laneNumber = 0;
else if(laneNumber >= lanesCount) laneNumber = lanesCount - 1;
}
} else {
didChangeLastFrame = false;
}
Vector3 pos = transform.position;
pos.x = Mathf.Lerp(pos.x, firstLaneXPos + laneDistance * laneNumber, Time.deltaTime * sideSpeed);
transform.position = pos;
How would I make that script work on clicking left/right side of the screen or swiping left/right?
Here's a little bit of code I've got for detecting if you click/tap on the left/right side of the screen:
moveVector.x = Input.GetAxisRaw ("Horizontal") * speed;
if (Input.GetMouseButton (0))
{
// Divide by 2 = right side // Else = left side
if (Input.mousePosition.x > Screen.width / 2)
moveVector.x = speed;
else
moveVector.x = -speed;
}
But the problem with this is that the player moves smoothly, it doesn't switch lanes like in the first script.
BTW. I'm a beginner at this.
Answer by Garazbolg · Nov 25, 2016 at 02:05 PM
Try this :
float input = Input.GetAxis("Horizontal");
if(Input.GetMouseButton(0)) //Just added these two lines
input += Input.mousePosition.x*2/Screen.width-1; // converting mouseX from
// [0;Screen[ to [-1;1[
// like the Input.GetAxis()
if(Mathf.Abs(input) > deadZone) {
if(!didChangeLastFrame) {
didChangeLastFrame = true; //Prevent overshooting lanes
laneNumber += Mathf.RoundToInt(Mathf.Sign(input));
if(laneNumber < 0) laneNumber = 0;
else if(laneNumber >= lanesCount) laneNumber = lanesCount - 1;
}
} else {
didChangeLastFrame = false;
}
Vector3 pos = transform.position;
pos.x = Mathf.Lerp(pos.x, firstLaneXPos + laneDistance * laneNumber, Time.deltaTime * sideSpeed);
transform.position = pos;
With this you should still have a dead zone in the middle of the screen (maybe for other interactions) and still have the behaviour that you had with the keyboard.
Also now on computer you can test the phone interaction by using the mouse as your finger.
Hope it helps you !
Do you know how to make it so that it only works for the bottom half of the screen? So divide the screen by 2 again but the other way and do nothing on the top half.