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
CodePudding user response:
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