- Home /
working on an endless runner. Need help with clamping.
private float edges = 7f;
public GameObject player;
public float movespeed = 10f;
private void Update()
{
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
//Vector3 change = player.transform.position;
Vector3 position = Input.GetTouch(0).position;
double halfscreen = Screen.width / 2;
Vector3 clamp = Input.GetTouch(0).position;
clamp.x = Mathf.Clamp(clamp.x, -edges, edges);
if(position.x < halfscreen)
{
player.transform.Translate(Vector3.left * movespeed * Time.deltaTime);
}
else if(position.x > halfscreen)
{
player.transform.Translate(Vector3.right * movespeed * Time.deltaTime);
}
}
}
That is the code that i have for my touch input and it works but I am able to go way past the edges of my map and i can't get the clamp to work... How would I implement this to make it so that touch input cant go past a certain point?
Answer by Nicole_W · May 14, 2018 at 07:47 PM
Hello,
Your question is a little ambiguous, so I've made two examples:
First, this will clamp the user input to be no more or less than 7 or -7 respectively:
private float edges = 7f;
public GameObject player;
public float movespeed = 10f;
private void Update() {
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
//Vector3 change = player.transform.position;
Vector3 position = Input.GetTouch(0).position;
double halfscreen = Screen.width / 2;
Vector3 clamp = Input.GetTouch(0).position;
clamp.x -= halfScreen;
clamp.x = Mathf.Clamp(clamp.x, -edges, edges);
if (clamp.x < halfscreen) {
player.transform.Translate(Vector3.left * movespeed * Time.deltaTime);
} else if (clamp.x > halfscreen) {
player.transform.Translate(Vector3.right * movespeed * Time.deltaTime);
}
}
This will still allow your player to move out of bounds however.
If your goal is to keep the player's position within 7 and -7 units on the x axis, try this instead:
private float edges = 7f;
public GameObject player;
public float movespeed = 10f;
private void Update() {
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
//Vector3 change = player.transform.position;
Vector3 position = Input.GetTouch(0).position;
double halfscreen = Screen.width / 2;
if (position.x < halfscreen) {
player.transform.Translate(Vector3.left * movespeed * Time.deltaTime);
} else if (position.x > halfscreen) {
player.transform.Translate(Vector3.right * movespeed * Time.deltaTime);
}
Vector3 playerPos = player.transform.position;
playerPos.x = Mathf.Clamp(playerPos.x, -edges, edges);
player.transform.position = playerPos;
}
}
Cheers and good luck!
Thank you so much! works perfectly! Now i am just trying to figure out why it feels slightly draggy...
Your answer
Follow this Question
Related Questions
Control the camera with a half of the touch screen 0 Answers
Clamping Issue 1 Answer
2D platformer controller script. How to jump with touch? 0 Answers
Touch controls 0 Answers
Raycast Touch Android not working JS 2 Answers