- Home /
want to move a player by holding a button. i created ascript but its only moving repeated tapping on the screen
using UnityEngine;
public class playermovement : MonoBehaviour { public playermovement movement; public Rigidbody rb; public float forwardForce = 100f; public float leftforce = 10f; public float rightforce = 10f;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
public void moveleft ()
{
if(Input.touchCount > 0)
{
if (Input.GetTouch(0).phase == TouchPhase.Began )
{
rb.AddForce(-leftforce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
}
Answer by Honorsoft · Jan 09, 2018 at 10:42 AM
Your 'public void moveleft()' function has all the input code, but it never gets called. It is a function that has to be called from somewhere in your project's objects/scripts. It is not like Unity's built-in functions like Update() and Start() which get called automatically (in a specific order), even if they are empty. You are recommended by Unity to put any Input related stuff in the Update() function because the inputs aren't cleared until the Update() function is called, therefore, if you handled the 'inputs' before the Update() function, there would be a period of time during play where the 'inputs' weren't reset after being pushed, until Update() was called again. So you would press 'fire' but nothing would happen kind of thing, it might not be much time, but every split-second counts in Online gaming, even at high speeds it can get laggy.
Try this:
using System.Collections; // These are commonly used..best to add them now
using System.Collections.Generic;
using UnityEngine;
public class playermovement : MonoBehaviour {
public playermovement movement;
public Rigidbody rb;
public float forwardForce = 100f;
public float leftforce = 10f;
public float rightforce = 10f;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
moveleft ();
}
}
void moveleft ()
{
if (Input.GetTouch(0).phase == TouchPhase.Began )
{
rb.AddForce(-leftforce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
}