- Home /
Character only moves a little when button is clicked.
Hello. I am making this mobile game and I have just started to get the character to move. I wanted to make the script so that when the button is clicked and held the character would move unless the button is no longer held. When I tested the script out the character only moves a little bit to the left instead of constantly moving to the left.
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour
{
public float speed = 5f;
public void OnMouseDown ()
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
}
All help is appreciated.
Answer by CJThomas · Aug 14, 2015 at 04:41 AM
OnMouseDown() only fires once when the mouse is pressed. You should try something like this.
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour
{
public float speed = 5f;
private bool mounseDown = false;
public void OnMouseDown ()
{
mouseDown = true;
}
public void OnMouseUp()
{
mouseDown = false;
}
public void Update()
{
if(mouseDown){
transform.position += Vector3.left * speed * Time.deltaTime;
}
}
}
Oh thanks! I had no idea it only fires once so that will help me a lot!
Answer by K-Rex · Aug 14, 2015 at 06:06 AM
Instead of using the "OnMouseDown" function/void (whatever you wanna call it) use "FixedUpdate". This is used commonly when moving gameobjects or characters. It's like the "Update" function but it will only be called 50 times per second so your character doesn't move faster if you are getting more frames per second. Now. For the actual question, inside the "FixedUpdate" function, say
if (Input.GetKey(KeyCode.Mouse0)) { transform.position += Vector3.left * speed * Time.deltaTime; }