【发布时间】:2021-07-14 13:38:22
【问题描述】:
我正在尝试制作 2D 自上而下的射击游戏。我首先实施了武器轮换,效果很好。然而,在实现角色精灵翻转后,武器精灵现在不会向右旋转,并且角色精灵变得很奇怪。我做错了什么?
角色移动脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
private Rigidbody2D rb;
Vector2 movement;
bool facingRight = true;
// Update is called once per frame
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (mousePos.x > transform.position.x && facingRight)
{
flip();
}
else if (mousePos.x > transform.position.x && !facingRight)
{
flip();
}
}
void flip()
{
facingRight = !facingRight;
transform.Rotate(0f, 180f, 0f);
}
private void FixedUpdate()
{
movement.Normalize();
rb.velocity = new Vector2(movement.x * speed * Time.fixedDeltaTime, movement.y * speed * Time.fixedDeltaTime);
}
}
武器轮换脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunRotation : MonoBehaviour
{
// Gun Rotation Function
public float offset;
private SpriteRenderer spriteRender;
// Start is called before the first frame update
void Start()
{
spriteRender = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
// Gun Rotation Function
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (rotZ < 89 && rotZ > -89)
{
Debug.Log("Facing right");
spriteRender.flipY = false;
}
else
{
Debug.Log("Facing left");
spriteRender.flipY = true;
}
}
}
【问题讨论】:
-
再次检查您的
if条件,了解您何时flip()。当您的鼠标位于精灵的右侧时,它将继续切换flip(),因为它们都具有相同的mousePos.x > transform.position.x条件。在这种情况下,您根本不需要检查facingRight,因为只有精灵和鼠标的相对位置很重要。 -
为什么要旋转播放器?为什么不采取相同的路线而只翻转精灵?然后相应地镜像
movement向量 -
@derHugo 谢谢你的评论。我通过观看 youtube 教程视频来做到这一点,因为我不知道如何实现这样的功能。如果您的想法更好,那么我很乐意这样做。但是由于我的水平无法理解您的想法,请您教我如何实现您的想法。