Q:

how to add movement in unity

//player must have a rigidbody2D and a box colider
public float moveSpeed = 5f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Jump();
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }

    void Jump()
    {
        if (Input.GetButtonDown("Jump"))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
        }
    }
20
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private string moveInputAxis = "Vertical";
    

    public float moveSpeed = 0.1f;
    public Rigidbody rb;
    public bool cubeIsOnTheGround = true;


    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    
    // Update is called once per frame
    void Update()
    {
       float moveAxis = Input.GetAxis(moveInputAxis); 

       ApplyInput(moveAxis);

       if(Input.GetButtonDown("Jump") && cubeIsOnTheGround == true)
       {
           rb.AddForce(new Vector3(0, 7, 0), ForceMode.Impulse);
           cubeIsOnTheGround = false;
       } 

    private void ApplyInput(float moveInput)
    {
        Move(moveInput);
    }

    private void Move(float input)
    {
        transform.Translate(Vector3.forward * input * moveSpeed);
    }    

    private void OnCollisionEnter(Collision collision) {
        if(collision.gameObject.tag == "Ground") {
            cubeIsOnTheGround = true;
        }
    }
}
0

New to Communities?

Join the community