With unity, C#, I want to switch the key operation of the arrow on the keyboard to button operation.

Asked 2 years ago, Updated 2 years ago, 125 views

You can use the arrow keys to move objects with the following code.
I want to be able to move this with the buttons up, down, right, and left, but I don't know how to edit the code.
Please let me know

public class OnKeyPress_Move—MonoBehavior
{
  public float speed = 2; 

  float vx = 0;
  floatby = 0;

  void Update()
  {
    vx = Input.GetAxisRaw("Horizontal")*speed;
    vy=Input.GetAxisRaw("Vertical")*speed;
  }
  private void FixedUpdate()
  {
    This.transform.Translate(vx/50,vy/50,0);
  }
}

c# unity3d unity2d

2022-09-30 20:18

1 Answers

If you're talking about Button, the code needs to be drastically changed.
You must attach the EventTrigger component to Button and move it while it is being pressed. (You can't do it with OnClick.)

Package: 82280.unitypackage

The package contains only the following codes:

using UnityEngine;

RequireComponent (type of (Rigidbody2D))]
public class ButtonMovement —MonoBehavior
{
    SerializeField float_speed=3f;
    Rigidbody2D_rb = default;

    void Start()
    {
        _rb = GetComponent <Rigidbody2D>();
    }

    public void Move (string dir)
    {
        Vector2velo=Vector2.zero;

        switch(dir)
        {
            case "Right":
                velo=Vector2.right;
                break;
            case "Left":
                velo=Vector2.left;
                break;
            case "Up":
                velo=Vector2.up;
                break;
            case "Down":
                velo=Vector2.down;
                break;
            default:
                break;
        }

        _rb.velocity=_speed*velo;
    }
}


2022-09-30 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.