簡體   English   中英

如何向移動方向旋轉 2D 精靈?

[英]How to Rotate 2D Sprite Towards Moving Direction?

我整天都在搜索並閱讀論壇,但我找不到有效的方法。 我正在制作一個自上而下的恐怖游戲。 當我的玩家正常行走時,他可以用光標向任何方向環顧四周,但當他想跑步時,他會切換到“坦克”控件並朝跑步方向旋轉。 我需要這樣的東西。 到目前為止,我的玩家移動腳本:

public float walkSpeed;
public float runSpeed;
public float turnSpeed;
private Rigidbody2D rb;
public Camera cam;
private Vector2 moveDirection;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    ProcessInput();
}

void FixedUpdate()
{
    Move();
}

private void ProcessInput()
{
    float moveX = Input.GetAxisRaw("Horizontal");
    float moveY = Input.GetAxisRaw("Vertical");

    moveDirection = new Vector2(moveX, moveY).normalized;
}
void Move()
{
    if (Input.GetKey(KeyCode.LeftShift))
    {
        //Looking toward movement direction should be applied here
    } else { 
        rb.velocity = new Vector2(moveDirection.x * walkSpeed, moveDirection.y * walkSpeed);

        Vector3 mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = mousePosition - transform.position;
        float angle = Vector2.SignedAngle(Vector2.right, direction) - 90f;
        Vector3 targetRotation = new Vector3(0, 0, angle);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(targetRotation), turnSpeed * Time.deltaTime);
    }
}

任何幫助是極大的贊賞! 提前致謝!

這個問題可以通過用moveDirection代替鼠標看方向來解決,這里定義一個名為 direction 的假設變量來檢測每個條件下的正確方向就足夠了。

var direction = new Vector2();
var currentSpeed = walkSpeed;

if (Input.GetKey(KeyCode.LeftShift))
{
    direction = moveDirection;

    currentSpeed = runSpeed;

} else {
    direction = cam.ScreenToWorldPoint(Input.mousePosition) - transform.position;
}

var angle = Vector2.SignedAngle(Vector2.right, direction) - 90f;
var targetRotation = new Vector3(0, 0, angle);
var lookTo = Quaternion.Euler(targetRotation);

rb.velocity = new Vector2(moveDirection.x, moveDirection.y) * runSpeed *Time.deltaTime;
transform.rotation = Quaternion.RotateTowards(transform.rotation, lookTo , turnSpeed * Time.deltaTime);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM