简体   繁体   English

如何向移动方向旋转 2D 精灵?

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

I have been searching all day and reading forums but I can't find a way that works.我整天都在搜索并阅读论坛,但我找不到有效的方法。 I'm making a top-down view horror game.我正在制作一个自上而下的恐怖游戏。 When my player walks normally he can look around with the cursor in any direction, but when he wants to run he switches to "tank" controls and rotates toward the running direction.当我的玩家正常行走时,他可以用光标向任何方向环顾四周,但当他想跑步时,他会切换到“坦克”控件并朝跑步方向旋转。 I need something like this .我需要这样的东西。 My player movement script so far:到目前为止,我的玩家移动脚本:

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

Any help is greatly appreciated!任何帮助是极大的赞赏! Thanks in advance!提前致谢!

This problem can be solved by substituting moveDirection instead of the mouse look direction, here it is enough to define a hypothetical variable called direction to detect the correct direction in each of these conditions.这个问题可以通过用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