Home > Back-end >  I want the "player" to move while the key is pressed Unity C#
I want the "player" to move while the key is pressed Unity C#

Time:03-01

how to make the "player" to move while the key is pressed and held? I have a button in the GUI

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moveLeft : MonoBehaviour
{
    public Transform player;

    public void Start(){
        player.transform.position = new Vector3 
        (player.position.x-1, player.position.y, player.position.z);
    }
}

CodePudding user response:

Input.GetKey(KeyCode.LeftArrow) means you hold left arrow key in keybord.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moveLeft : MonoBehaviour
{
public Transform player;

[SerializableField] float speed;

void Update(){
    if(Input.GetKey(KeyCode.LeftArrow))
        player.transform.position  = Vector3.left * speed * Time.deltaTime;
}
}

Edit:

using UnityEngine;
using UnityEngine.EventSystems;

public class moveLeft : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public Transform player;

[SerializableField] float speed;

void Update(){
    if(isActive)
        player.transform.position  = Vector3.left * speed * Time.deltaTime;
}

bool isActive = false;
public void OnPointerDown(PointerEventData eventData)
{
    isActive = true;
}

public void OnPointerUp(PointerEventData eventData)
{
    isActive = false;
}

}
  • Related