- Home /
How to move character horizontally with Touch, while player always runs forward?
Hey guys,
So what I am doing is an Android Game, where I have a player, who runs forward since the start of game. I do this with following code:
void Update () {
// Assign player to always go forward, continously
transform.position += transform.forward * Time.deltaTime * speed;
}
Now I would like to receive Touch Inputs from Android Devices and I only care (for now) about x direction (so left and right, based on where on the screen was touched).
I have found several answers here on Unity3D, but each of those I tried, did not have the effect I want to achieve (= so to continue running forward, but just moving the position to either left or right).
User should hold the finger to continue moving left or right... touching the screen only, should just move the player for a slight distance.
Any advice?
Thanks
Answer by Hellium · Jan 18, 2017 at 03:42 PM
You can try something like this :
Vector3 deltaPosition = transform.forward * forwardSpeed;
if( Input.touchCount > 0 )
{
Vector3 touchPosition = Input.GetTouch( 0 ).position;
if ( touchPosition.x > Screen.width * 0.5f )
deltaPosition += transform.right * sideSpeed;
else
deltaPosition -= transform.right * sideSpeed;
}
transform.position += deltaPosition * Time.deltaTime ;
Better than others I have tried, but I still have a bit strange issue, because when I touch right-side of screen, it drags character somehow forward-right, not just right. And if I do left-touch, it goes backwards-left. Does the sideSpeed need to be equal forwardSpeed?
I edited my answer, I made a huge mistake when setting only the x coordinate of the delta vector.
Answer by nathi0106 · Feb 14, 2019 at 06:50 PM
Hi. I'm also trying to android-ify my horizontal-movement-game... But can't.. (I'm a noob in unity and scripting btw). Since, this script is working, I would like to ask, do i have to define forward speed and also side speed as 2 different variables?? I desperately need help on this. I have attached the script i used to move my character using keyboard. Please help. Thanks in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicMovement : MonoBehaviour {
public Animator animator;
public float speed;
private void Start()
{
}
// Update is called once per frame
void Update () {
animator.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
Vector3 horizontal = new Vector3(Input.GetAxis("Horizontal"), 0.0f, 0.0f);
transform.position = transform.position + horizontal * speed * Time.deltaTime;
}
}
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Separate Objects after Mouse Clicking in Unity 5.6.4 1 Answer
Problem with movement 0 Answers
Player not following touch after camera is rotated? 0 Answers
Multiple Cars not working 1 Answer