© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
23 replies
uǝsuıɟlnℲ

❔ 2D player movement

Hello. I am following an Unity course for making a 2D game and I am at the part where I need to make my player move. I have wrote the code, but I get the same error on 2 lines of code: Cannot access non-static method blank in static context. This is the code (I am getting that error on var absVelX = Mathf.Abs(Rigidbody2D.velocity.x); at velocity and Rigidbody2D.AddForce(new Vector2(forceX, forceY)); at AddForce:

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

public class Player : MonoBehaviour
{
    public float speed = 10f;
    public Vector2 maxVelocity = new Vector2(3, 5);
    

    // Update is called once per frame
    void Update()
    {
        var forceX = 0f;
        var forceY = 0f;

        var absVelX = Mathf.Abs(Rigidbody2D.velocity.x);
        
        
        if (Input.GetKey("right"))
        {
            if (absVelX < maxVelocity.x)
                forceX = speed;
        }else if (Input.GetKey("left"))
        {
            if (absVelX < maxVelocity.x)
                forceX = -speed;
        }

        Rigidbody2D.AddForce(new Vector2(forceX, forceY));
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float speed = 10f;
    public Vector2 maxVelocity = new Vector2(3, 5);
    

    // Update is called once per frame
    void Update()
    {
        var forceX = 0f;
        var forceY = 0f;

        var absVelX = Mathf.Abs(Rigidbody2D.velocity.x);
        
        
        if (Input.GetKey("right"))
        {
            if (absVelX < maxVelocity.x)
                forceX = speed;
        }else if (Input.GetKey("left"))
        {
            if (absVelX < maxVelocity.x)
                forceX = -speed;
        }

        Rigidbody2D.AddForce(new Vector2(forceX, forceY));
    }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

2D Movement
C#CC# / help
11mo ago
❔ 2D top down movement issue
C#CC# / help
3y ago
❔ 2D Dictionary
C#CC# / help
3y ago