Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

c# - Set rigidbody.velocity to direction of mouse in Unity2d: Updated Version

Yes I know this question was asked before by SuperSonyk! That post is here: Set rigidbody.velocity to direction of mouse in Unity2d

However- the link referenced in the answer to that post is now legacy material, and I can't bring myself to understand it in Unity's current version.

My Problem: In short, I want to make my player accelerate in the direction of my cursor. My game is currently a TOP-DOWN Space Shooter in 2D. My player already looks at my mouse correctly, using cam.ScreenToWorldPoint. But relentlessly trying to add force seems futile for me, since I am fairly new to coding.

If I have any other issues in my code, It would be great if anyone could point them out! Here's my code:

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

public class PlayerController : MonoBehaviour
{
    //================= MOVEMENT =====================
    private float thrust = 0.5f;
    private float maxSpeed = 10f;
    public Rigidbody2D rb;

    //================= AIMING =======================
    public Camera cam;
    Vector2 mousePos;

    // Update is called once per frame: Good for INPUTS
    void Update()
    {
        //aiming
        mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    }
    // Called Set amount of times. Good for PHYSICS CALCULATIONS
    void FixedUpdate()
    {
        Move();
        speedLimiter();

        //aim
        Vector2 lookDirection = mousePos - rb.position;
        float angle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg - 90f;
        rb.rotation = angle;
    }
    //======= MY MOVE FUNCTION DOES NOT WORK. HELP? ======
    void Move()
    {
        if (Input.GetButtonDown("Accelerate"))
        {
            rb.velocity = new Vector3(0, thrust, 0) * Time.deltaTime;
        }
    }
    void speedLimiter()
    {
        if (rb.velocity.magnitude > maxSpeed)
        {
            rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
        }
    }
}

Please summarize the edits clearly, thank you!

question from:https://stackoverflow.com/questions/65902542/set-rigidbody-velocity-to-direction-of-mouse-in-unity2d-updated-version

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In general since this is a 2D rigidbody also the velocity is a Vector2 and you should probably rather use Vector2.ClampMagnitude

and then in

rb.velocity = new Vector3(0, thrust, 0) * Time.deltaTime; 

do you only want to move in global Y direction? Also a velocity is already a "per second" value -> it makes no sense to multiply by Time.deltaTime if you reassign a new velocity. Since it says thrust I guess you rather wanted to add to the existing velocity.


What you would rather do is save your mouse direction you already have and do

public class PlayerController : MonoBehaviour
{
    ...

    void FixedUpdate()
    {
        // I would update the aim BEFORE moving
        // Use a NORMALIZED direction! Makes things easier later
        Vector2 moveDirection = (mousePos - rb.position).normalized;
        float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg - 90f;
        rb.rotation = angle;

        // OPTIONAL: Redirect the existing velocity into the new up direction 
        // without this after rotating you would still continue to move into the same global direction    
        rb.velocity = rb.velocity.magnitude * moveDirection;

        Move(moveDirection);
        speedLimiter();
    }
    
    void Move(Vector2 moveDirection)
    {
        if (Input.GetButtonDown("Accelerate"))
        {
            // Instead of re-assigning you would probably add to the existing velocity
            // otherwise remove the "+" again
            rb.velocity += moveDirection * thrust * Time.deltaTime;
        }
    }

    void speedLimiter()
    {
        if (rb.velocity.magnitude > maxSpeed)
        {
            // You are working with Vector2 so use the correct method right away
            rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...