- Home /
Stop Moving When Not Touching Screen?
So i'm trying to make it so that every time you touch the screen it will move instead of constantly moving like it does now. When I tried to put the translation into an if (touch) statement it would only work and move one frame every touch, while I would like it to be constantly moving and following when the screen is touched. Here is my code:
//Gathering resources
using UnityEngine;
using System.Collections;
//The Move class decleration
public class Move : MonoBehaviour
{
//How quickly the player follows the mouse
public float Speed = 20;
private float moveSpeed = 10;
private bool touching = false;
/**
* ADD THE ABILITY TO STOP MOVING IF NOT TOUCHING SOMEWHERE ON THE SCREEN, POSSIBLY WITH A WHILE TOUCHING METHOD AT THE BEGINNING
* */
//Called every frame
void Update()
{
if (Input.mousePresent && Input.anyKeyDown)
{
touching = true;
}
else
{
touching = false;
}
if (Input.mousePresent)
{
movePlayer();
}
}
private void movePlayer()
{
//Converting mouse position into Vector3
Vector3 Target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//Fixing Z-Axis
Target.z = transform.position.z;
Speed = (moveSpeed +(moveSpeed *(Vector3.Distance(Target, transform.position))));
//Actually move the player towards the mouse.
transform.position = Vector3.MoveTowards(transform.position, Target, Speed * Time.deltaTime / transform.localScale.x);
}
}
Answer by LCStark · Sep 29, 2018 at 09:37 PM
Input.anyKeyDown
returns true
only during the single frame when a button is pressed, so that's why your movement only works during a single frame every touch. If you want to hold the button to move, use Input.anyKey
instead.
Since you want to use a touch screen, why don't you use Input.GetTouch instead?
Your answer
Follow this Question
Related Questions
Move with Rigidbody2D in the Z axis 3 Answers
Simple movement problem. Need units to stop dead on collision. 3 Answers
Dash in the direction of a parents child object 1 Answer
How can I rotate my player to look at the direction my Joystick is pointing to? (Top-Down 2D) 3 Answers
How can i fix a position of a gameobject after it meets its condition 1 Answer