- Home /
How to restrict touch movement for android.
Hey, i am working on a 2D car racing game for android device. I have coded the touch movement for my car. But the problem is the car is going beyond the track. How can i restrict the car movement, i mean how can i code for my car to stay in the screen(Screen resulation is 480*800 and car sprites max position is 4.2 and min -4.2). Here r my C# car controller script. using UnityEngine; using System.Collections;
public class carController : MonoBehaviour {
public float carSpeed;
// Update is called once per frame
void Update () {
if (Input.touchCount == 1) {
Touch touch = Input.touches[0];
if(touch.position.x < Screen.width/2){
transform.position += Vector3.left * carSpeed * Time.deltaTime;
}
else if(touch.position.x > Screen.width/2){
transform.position += Vector3.right * carSpeed * Time.deltaTime;
}
}
}
}
Answer by Evansbsr · Aug 16, 2015 at 06:26 PM
Use colliders to define the boundaries of the track
Thanks for your answer. I have tried that solution. But the problem is it's actually working in case of single touch. If i touch for a long time my car gone beyond the street and the boundaries failed to stay the car inside the screen.
Store the x position in a temporary variable and clamp this to the boundaries you'd like before applying it to the transform
public float carSpeed;
float _x;
// Update is called once per frame
void Update () {
if (Input.touchCount == 1) {
_x = transform.position.x;
Touch touch = Input.touches[0];
if(touch.position.x < Screen.width/2){
_x -= carSpeed * Time.deltaTime;
}
else if(touch.position.x > Screen.width/2){
_x += carSpeed * Time.deltaTime;
}
_x = $$anonymous$$athf.Clamp(_x, -4.2f, 4.2f);
transform.position = new Vector3(_x, transform.position.y, transform.position.z);
}
}
Answer by saschandroid · Oct 01, 2015 at 08:58 AM
if(touch.position.x < Screen.width/2)
{
transform.position += Vector3.left * carSpeed * Time.deltaTime;
if ( transform.position.x < -4.2f )
{
transform.position = new Vector3(-4.2f, transform.position.y, transform.position.z);
}
}
else if(touch.position.x > Screen.width/2)
{
transform.position += Vector3.right * carSpeed * Time.deltaTime;
if ( transform.position.x > 4.2f )
{
transform.position = new Vector3(4.2f, transform.position.y, transform.position.z);
}
}