【发布时间】:2019-08-12 19:07:58
【问题描述】:
我正在尝试创建一个 2D 自上而下的射击游戏。我想为玩家设置一种方式,让玩家将枪指向他移动的方向。例如,如果玩家按住 W 和 A 键,他的枪指向右上角。当他在方向之间切换时,枪也平滑地切换。如果玩家直线上升(例如按住 W 键),则整个玩家会切换方向。
我已经成功地复制了这一点,但仅限于 6 个方向。但是,我想让玩家的移动和所有其他方向都变得平滑。 我知道必须有一个简单的答案,我就是想不通。这是我的代码,函数以其用途命名:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Character Attributes:")]
public float movementBaseSpeed = 1.0f;
[Space]
[Header("Weapon Statistics:")]
public float upwardSideAngle = 30f;
public float downwardSideAngle = -30f;
public float idleAngle = -10f;
[Space]
[Header("Character Statistics:")]
public Vector2 currentMovementDirection;
public float currentMovementSpeed;
[Space]
[Header("References:")]
public Rigidbody2D rb;
public Animator animator;
public GameObject weapon;
// Update is called once per frame
void Update()
{
ProcessInputs();
Move();
Animate();
MoveAim();
}
void ProcessInputs()
{
currentMovementDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
currentMovementSpeed = Mathf.Clamp(currentMovementDirection.magnitude, 0.0f, 1.0f);
currentMovementDirection.Normalize();
}
void Animate()
{
if (currentMovementDirection != Vector2.zero)
{
animator.SetFloat("Horizontal", currentMovementDirection.x);
animator.SetFloat("Vertical", currentMovementDirection.y);
}
animator.SetFloat("Magnitude", currentMovementDirection.magnitude);
}
void Move()
{
rb.velocity = currentMovementDirection * currentMovementSpeed * movementBaseSpeed;
}
void MoveAim()
{
//When player is moving left
if(currentMovementDirection.x < 0)
{
weapon.transform.rotation = Quaternion.Euler(0, 180, 0);
}
//When player is moving right
else if(currentMovementDirection.x > 0)
{
weapon.transform.rotation = Quaternion.identity;
}
//When player is moving top right
if(currentMovementDirection.y > 0 && currentMovementDirection.x > 0)
{
weapon.transform.rotation = Quaternion.Euler(0f, 0f, upwardSideAngle);
}
//When player is moving bottom right
if(currentMovementDirection.y < 0 && currentMovementDirection.x > 0)
{
weapon.transform.rotation = Quaternion.Euler(0f, 0f, downwardSideAngle);
}
//When player is moving top left
if(currentMovementDirection.y > 0 && currentMovementDirection.x < 0)
{
weapon.transform.rotation = Quaternion.Euler(0, 180, upwardSideAngle);
}
//When player is moving bottom left
if (currentMovementDirection.y < 0 && currentMovementDirection.x < 0)
{
weapon.transform.rotation = Quaternion.Euler(0, 180, downwardSideAngle);
}
//When player is standing still
if (currentMovementDirection.y == 0 && currentMovementDirection.x == 0)
{
weapon.transform.rotation = Quaternion.Euler(0f, 0f, idleAngle);
}
}
}
【问题讨论】:
标签: c# unity3d game-development