0

I've just started learning Unity and I want to create a mobile touch game that restricts the players movement within a certain area.

I can achieve this when the input is tied to the arrow keys (using a 2D Collider box and the code below).

float steerSpeed = 10f;
float moveSpeed = 10f;
void Update()
{
        float steerAmount = Input.GetAxis("Horizontal") * steerSpeed * Time.deltaTime;
        float moveAmount = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
        transform.Translate(steerAmount, moveAmount, 0); 
}

However, when I use touch input, the object passes right through and ignores the box with the collider (touch code below).

    void Update()
    {
    if (Input.touchCount > 0) {
        Touch touch = Input.GetTouch(0);
        Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
        touchPosition.z = 0f;
        transform.position = touchPosition;
    }

}

Any ideas why the touch controls allow the object to ignore the 2D collider box (and what would be the best way to achieve my goal)?

Thanks!

Logan
  • 1
  • Your problem is the same as the one discussed here - moving an object with its transform is a teleport, not a slide. The reason it appears to work with the arrow keys is that your moveSpeed is low enough that the object penetrates only a short distance into the collider after the teleportation, and on the next physics step the physics engine is able to push it back out the correct side. But your touch controls have unbounded speed - potentially teleporting across the whole screen in one jump, so there's no overlap to detect and correct. – DMGregory Mar 30 '23 at 13:35
  • Which also, I think, theoretically means that for a sufficiently long deltaTime between frames, the first set of code could escape the bounds too. Not great! – Onyz Mar 30 '23 at 16:26

0 Answers0