简体   繁体   中英

How to do rb.AddForce but for 2D? Unity C#

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");
        }
    }
}

Rigidbody2D.AddForce doesn't take two float parameters but rather as usual a Vector2 and a ForceMode2D where the latter has a default value of ForceMode2D.Force if you don't pass it in.

So your code should rather be

//          = new Vector2 (0,1) * moveSpeed
//          = new Vector2 (0, moveSpeed)
rb.AddForce(Vector2.up * moveSpeed);

...

// I assume in the second case you rather want to go down so
//           = new Vector2 (0, -1) * moveSpeed
//           = new Vector2 (0, -moveSpeed)
rb.AddForce(Vector2.down * moveSpeed);

Btw I would rather not Debug.Log every frame in Update it's pretty expensive.

You can add a new Vector2 in rb.AddForce (new Vector2(0,moveSpeed));

Here is the updated code:

 public class Movement : MonoBehaviour
    {
        public Rigidbody2D rb;
        public Collider2D collider;

        public float moveSpeed = 0.1f;

        private void Update()
        {
            if (Input.GetKey("w"))
            {
                rb.AddForce(new Vector2(0f, moveSpeed));
                Debug.Log("w");
            }

            if (Input.GetKey("s"))
            {
                rb.AddForce(new Vector2 (0f, moveSpeed));
                Debug.Log("s");
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM