[英]2d shooter mouse follow issues. Unity 2d
I am making a 2d shooter but I have run into an issue.我正在制作 2d 射击游戏,但遇到了问题。 When my character flips its scale to -1 when going left the rotation of the weapon hold inverts away from the cursor. Here is the mouse follow code I have in case it is needed.
当我的角色在向左移动时将其比例翻转为 -1 时,武器的旋转保持反转远离 cursor。这是我的鼠标跟随代码,以备不时之需。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public float offset;
void Update()
{
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);
}
Any help is use full.任何帮助都是充分利用的。
Use Mathf.Sign
to take the sign of the x scale into account when calculating the rotation.使用
Mathf.Sign
在计算旋转时考虑 x 比例的符号。 You will use it to negate x component of the rotation and the angle of rotation itself when the scale is flipped:当比例尺翻转时,您将使用它来否定旋转的 x 分量和旋转角度本身:
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition)
- transform.position;
float scaleSign = Mathf.Sign(transform.localScale.x);
float rotZ = Mathf.Atan2(difference.y, difference.x * scaleSign) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, (rotZ + offset) * scaleSign );
Add this to your code.将此添加到您的代码中。
if (rotZ < -90f || rotZ > 90f)
{
if (playerGameObject.transform.eulerAngles.y == 0f)
{
transform.localRotation = Quaternion.Euler (180f, 0f, rotZ);
}
else if (playerGameObject.transform.eulerAngles.y == 180f)
{
transform.localRotation = Quaternion.Euler (180f, 180f, -rotZ);
}
}
The full thing would be like this完整的东西是这样的
public float offset;
void Update()
{
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 < -90f || rotZ > 90f)
{
if (playerGameObject.transform.eulerAngles.y == 0f)
{
transform.localRotation = Quaternion.Euler (180f, 0f, rotZ);
}
else if (playerGameObject.transform.eulerAngles.y == 180f)
{
transform.localRotation = Quaternion.Euler (180f, 180f, -rotZ);
}
}
}
This code changes the way you are rotating the gun if the player is flipped.如果玩家被翻转,这段代码会改变你旋转枪的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.