Should Not Be Capturing When There Is a Hotcontrol - Unity

I am pretty new to Unity and C#. I already know python, so C# was quite easy to grasp, but now I have a problem. I am not able to run this code. It is is causing an error to appear. I checked the code many times but couldn't find the issue. Here is the code:

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


public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb2D;

    private float moveSpeed;
    private float moveHorizontal;
    private float moveVertical;

    // Start is called before the first frame update
    void Start()
    {
        moveSpeed = 3f;
        rb2D = gameObject.GetComponent<Rigidbody2D>();

    }

    // Update is called once per frame
    void Update()
    {

    }

    void FixedUpdate()
    {
        moveHorizontal = Input.GetAxisRaw("Horizontal");

        if (moveHorizontal > 0.1f || moveHorizontal < -0.1f)
        {
            rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed), ForceMode2D.Impulse);
        }
    }
}

The floor (White rectangle) is a rigidbody and box collider. So is the player (Red square). I want to move the square using the keyboard.

Any help will be appreciated

1 Answer

The issue is here:

 rb2D.AddForce(new Vector2(moveHorizontal * moveSpeed), ForceMode2D.Impulse);

Vector2's take 2 floats as input. To fix it, you have to do this

new Vector2(moveHorizontal * moveSpeed, moveVertical * moveSpeed)

You forgot to define the vertical movement in the vector2

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest