- Home /
How do I do rb.AddForce but in 2D?
I am making a 2D game where you control a shield and you have to block falling obstacles from reaching base. I know that to move something you use rb.addforce
. However, when I do the same for 2D it doesn't work. I imagine that instead of using a Vector3 you use a Vector2, but it gives me these 2 errors: Assets\Movement.cs(16,25): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector2'
and this one: Assets\Movement.cs(16,25): error CS1503: Argument 1: cannot convert from 'float' to 'UnityEngine.Vector2'
for each time I write the line. Here is my full code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public Rigidbody2D rb;
public Collider2D collider;
public float moveSpeed = 0.1f;
private void Update()
{
if (Input.GetKey("w"))
{
rb.AddForce(0f, moveSpeed);
Debug.Log("w");
}
if (Input.GetKey("s"))
{
rb.AddForce(0f, moveSpeed);
Debug.Log("s");
}
}
}
Answer by tadadosi · Jun 24, 2020 at 04:10 AM
Rigidbody2D.AddForce takes two arguments, the first one is a Vector2 and the second is the type of force that will be used AddForce(Vector2 force, ForceMode2D mode = ForceMode2D.Force);
0
In order to use this method you need to provide a Vector2 for the direction of the force and multiply that by your moveSpeed (Which I think should be called moveForce
instead).
rb2D.AddForce(Vector2.right * moveForce);
Your answer
Follow this Question
Related Questions
C# 2D Translate Forward Based on Rotation 1 Answer
Inconsistent wallJumping, vector sends in wrong direction 0 Answers
how do i keep a gameobject in between the union of 2 or more than 2 circles 0 Answers
Rigidbody2D.Velocity = Vector2 not changing X Position 1 Answer
Push an Object with a vector created from two points. 0 Answers