简体   繁体   中英

Trying to launch in the mouse position in Unity

I am trying to get the player character to launch in the direction of the mouse based on a launch range.

The problem is that I do not know how I would go about doing this. I attempted it anyway and here is the code I came up with.

public class playershoot : MonoBehaviour
{
   public float shootRange = 5f;

   Vector2 shootDir;
   Vector2 lookDir;
   public Rigidbody2D rb;
   public Camera cam;

   Vector2 mousePos;
   void FixedUpdate()
   {
       System.Diagnostics.Debug.WriteLine("huzza!");
       mousePos = cam.ScreenToWorldPoint(Input.mousePosition);

       if (Input.GetMouseButtonDown(0))
           System.Diagnostics.Debug.WriteLine("huzza!");
           lookDir = mousePos - rb.position;
           rb.MovePosition(rb.position + lookDir * shootRange);
    }
}

I know it looks really bad and I was going to clean it up a lot once I got it working. Unfortunately, I never got to that point. Any tips?

We don't have much context about your problem, but there is one thing that catches attention in you if statement.

void FixedUpdate()
{
    System.Diagnostics.Debug.WriteLine("huzza!");
    mousePos = cam.ScreenToWorldPoint(Input.mousePosition);

    if (Input.GetMouseButtonDown(0))
       System.Diagnostics.Debug.WriteLine("huzza!");
       lookDir = mousePos - rb.position;
       rb.MovePosition(rb.position + lookDir * shootRange);
}

In c#, if you want to execute many statements inside an if statement, you need to enclose a scope with curly brackets { }. Otherwise, only the first statement after the if will be considered by the if.

With this code as is, only the line System.Diagnostics.Debug.WriteLine("huzza;"); will be conditionally executed when Input.GetMouseButtonDown(0) is true. The following two lines are executed outside the if. That means, no matter if input is captured or not, rb.MovePosition will happen on every frame by update.

You probably meant this:

    if (Input.GetMouseButtonDown(0))
    {
       System.Diagnostics.Debug.WriteLine("huzza!");
       lookDir = mousePos - rb.position;
       rb.MovePosition(rb.position + lookDir * shootRange);
    }

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