简体   繁体   中英

How to raycasting to player facing direction?

in my 2D topdown game, I'm trying to cast a ray from my player to the direction he is facing. all going great yet the problem is the moment the player stop moving the raycast stopped(which makes sense I'm using Input.GetAxis which returns value of 0 when stop moving). I've been trying using Transform.right / TransformDirection its just makes the ray to stick at the same position and not where the player facing. is there any way for me to keep the ray cast keep going even if my player is stop moving?

 public Collider2D GetBarrleCollider() { Physics2D.queriesStartInColliders = false; RaycastHit2D hit = Physics2D.Raycast(this.transform.position, movement, playerDistance); if (hit.collider != null && hit.collider.gameObject.CompareTag("Pickup")) { Debug.Log("Return NOT null" + " " + hit.collider.tag); return hit.collider; } else { Debug.Log("Return null"); return null; } }

 public void MovementHandler() { movement.x = Input.GetAxisRaw("Horizontal"); movement.y = Input.GetAxisRaw("Vertical"); rb2D.MovePosition(rb2D.position + movement * getPlayerMovementSpeed * Time.deltaTime); }

You would store the direction as a variable. Lets call it lookDir . Then you should check if the movement vector is not zero:

Vector2 lookDir;

public void MovementHandler()
{
    movement.x = Input.GetAxisRaw("Horizontal");
    movement.y = Input.GetAxisRaw("Vertical");
    rb2D.MovePosition(rb2D.position + movement * getPlayerMovementSpeed * Time.deltaTime);

    if (movement != Vector2.zero)
    {
        lookDir = movement;
    }
}

Then you could raycast from this vector. This way, you only change it if the player is moving.

Something like this should work:

public void MovementHandler()
{
    movement.x = Input.GetAxisRaw("Horizontal");
    movement.y = Input.GetAxisRaw("Vertical");
    rb2D.MovePosition(rb2D.position + movement * getPlayerMovementSpeed * Time.deltaTime);

    if (movement != Vector2.zero)
    {
        lookDir = movement;
    }
}
public Collider2D GetBarrleCollider()
{
    Physics2D.queriesStartInColliders = false;

    //this line was changed \/
    RaycastHit2D hit = Physics2D.Raycast(this.transform.position, lookDir, playerDistance);
    //

    if (hit.collider != null && hit.collider.gameObject.CompareTag("Pickup"))
    {
        Debug.Log("Return NOT null" + " " + hit.collider.tag);
        return hit.collider;
    }
    else
    {
        Debug.Log("Return null");
        return null;
    }
}

Let me know in the comments if this doesn't work.

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