using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(1000, 0);
}
}
So I just started unity a day ago and I want to make a game that has a character (block) automatically moving on a platform and the player has to dodge obstacles and such (such an original idea right?), but so far I just got the platform ready and the player whoâs supposed to move, Iâm still on the first step which is figuring out who to make the player move automatically to the right, the component is being added to âPlayerâ and I keep getting that error on the title of this thread. I would appreciate it if someone could just send me the full code that I should write and I would appreciate it much much more if I were to be told whatâs exactly wrong so I donât make any future mistakes similar to this one (2D game btw).
Everything Is indented correctly btw i donât know why my post on preview is shown without indentation
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
// Update is called once per frame
void FixedUpdate()
{
vector3 vf = new vector3(1000,0,0);
rb.AddForce(vf);
}
}
add force takes a vector because it needs direction, in this case a vector is a (x,y,z) direction and you are specifying 1000 units of force toward the right.
it would be cleaner like this:
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
// Update is called once per frame
void FixedUpdate()
{
float force = 10f;
rb.AddForce( vector3.right * force);
}
}
this assumes your direction is going right and multiplies it by the amount of force you want to apply
When posting code it doesnât automatically recognise code. Hereâs how you use Code Tags .
So to be clear, this isnât a âUnityâ thing, itâs a C# language thing. You called Rigidbody2D.AddForce() but if you look at the docs, it doesnât take an int (you passed â1000â) but instead takes a Vector2. The Vector2 is a direction and magnitude of the force you want to apply.
EDIT: I noticed you got a reply just before mine. Note that this is mostly correct but you should use Vector2 instead of âvector3â (note that it is case sensitive too). Unity will convert Vector3 to Vector2 by dropping the Z but this can be the source of subtle issues sometimes so stick to Vector2 where it makes sense.