PlayerMovement Script I made isn't working!

Welcome!

First, please use code tags when sharing code on the forums. It makes it much easier for us to read.

I give everyone one free formatting, so here’s yours:

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

public class Player_Move : MonoBehaviour {
    public Rigidbody2D rb;
    public float sidewaysForce = 500f;

    void FixedUpdate () {
        if (Input.GetKey("d")) {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0);
        }

        if (Input.GetKey("a")) {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0);
        }
    }
}

Your error is on line 11 of my version (line 16 of yours), and also line 15 (your 21). Let’s look at the error messages:

They’re kinda both the same thing here, but one’s telling you generally what’s wrong, and the other is telling you specifically where the compiler is having issues.

You’re using the method AddForce, which belongs to the Rigidbody2D class. If you look up that method in the documentation (and, helpfully, in the first error message itself!), you’ll see it requires one parameter of type Vector2, and can take an optional second parameter of type ForceMode2D).

Look at your second error message. It’s telling you that it can’t convert your float type to Vector2. My guess is you’re trying to pass just the X value in as the first parameter, and 0 in the second to have no Y value movement. The problem is that you forgot to wrap those values in a Vector2, so you’re not actually doing what it is you think you’re doing. If you do so, I bet it works for you (or at the very least, doesn’t give you errors).

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

public class Player_Move : MonoBehaviour {
    public Rigidbody2D rb;
    public float sidewaysForce = 500f;

    void FixedUpdate () {
        if (Input.GetKey("d")) {
            rb.AddForce(new Vector2(sidewaysForce * Time.deltaTime, 0));
        }

        if (Input.GetKey("a")) {
            rb.AddForce(new Vector2(-sidewaysForce * Time.deltaTime, 0));
        }
    }
}
3 Likes