- Home /
Question by
Guilherme_Aguiar · Jan 19, 2017 at 05:22 AM ·
movementnewbietouch controlsdiagonal
How could I implement diagonal movement in this code?
public class PlayerC : MonoBehaviour
{
public Vector2 startPos;
public Vector2 endPos;
public bool fingerHold = false;
public float speed = 50f;
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
startPos = touch.position;
fingerHold = true;
}
else if (touch.phase == TouchPhase.Moved)
{
endPos = touch.position;
}
else if (touch.phase == TouchPhase.Ended)
{
fingerHold = false;
}
}
if (fingerHold)
{
float deltaX = endPos.x - startPos.x;
float deltaY = endPos.y - startPos.y;
bool horizontal = false;
if (Mathf.Abs(deltaX) > Mathf.Abs(deltaY))
horizontal = true;
if (horizontal)
{
if (deltaX < 0)
transform.Translate(Vector3.left * Time.deltaTime * speed);
else if (deltaX > 0)
transform.Translate(Vector3.right * Time.deltaTime * speed);
}
else
{
if (deltaY < 0 )
transform.Translate(Vector3.down * Time.deltaTime * speed);
else if (deltaY > 0 )
transform.Translate(Vector3.up * Time.deltaTime * speed);
}
}
}
}
Comment
Answer by steo · Jan 19, 2017 at 09:53 AM
If you want to move in any direction, use this code block:
if (fingerHold) {
float deltaX = endPos.x - startPos.x;
float deltaY = endPos.y - startPos.y;
Vector2 direction = new Vector2(deltaX, deltaY).normalized;
transform.Translate(direction * Time.deltaTime * speed);
}
If yout want to move in 8 directions, use this block:
if (fingerHold) {
float deltaX = endPos.x - startPos.x;
float deltaY = endPos.y - startPos.y;
Vector2 direction = new Vector2(deltaX, deltaY).normalized;
direction = new Vector2(
x: Mathf.Round(direction.x),
y: Mathf.Round(direction.y)
);
transform.Translate(direction * Time.deltaTime * speed);
}