【发布时间】:2015-09-22 15:34:27
【问题描述】:
我正在设计 2D 游戏中玩家瞄准和射击的逻辑。当用户在屏幕上单击并拖动时,它应该围绕精灵旋转一条由 3 个点组成的线,与玩家拖动的角度相同,以便他可以瞄准。就像在泡泡射击游戏中一样。
“Player”预制件有一个名为“Sight”的子对象,它是一个将 4 个点精灵作为具有相应偏移量的子对象的变换,因此旋转“Sight”将旋转整条线。
在我查看的每个更新循环中,视线根据鼠标位置旋转,但变量视线似乎为空。我试图通过标签获取对象,并拥有一个公共变量,这样我就可以从检查器中分配预制件。我也试图只抓住变换组件。我确信这是一个非常愚蠢的问题,但我看不到它。我将不胜感激。
瞄准逻辑:
public class PlayerShooting : MonoBehaviour {
public GameObject BulletPrefab;
public float coolDownTimer = 0.0f;
public float aimDistance = 0.5f;
private Vector2 originPoint = new Vector2 (0f,0f);
private Vector2 endPoint = new Vector2(0f,0f);
private bool dragging = false;
public GameObject sight;
// Update is called once per frame
void Update () {
// TOUCH DOWN
if (Input.GetMouseButtonDown(0) == true) {
originPoint = getPointInWorld(Input.mousePosition);
endPoint = originPoint;
dragging = true;
}
// TOUCH UP
if (Input.GetMouseButtonUp(0) == true) {
endPoint = getPointInWorld(Input.mousePosition);
dragging = false;
FireBullet();
}
// DRAGGING
if (dragging) {
endPoint = getPointInWorld(Input.mousePosition);
// AIM
// !!!: THIS IS THE ISSUE
sight = GameObject.Find("Player/Sight");
if (sight != null && endPoint != originPoint) {
Vector2 dir = originPoint - endPoint;
dir.Normalize();
float zAngle = Mathf.Atan2 (dir.y,dir.x) * Mathf.Rad2Deg - 90;
Quaternion newRotation = Quaternion.Euler(0,0,zAngle);
sight.transform.rotation = newRotation;
}
else
{
Debug.Log("Error: cannot aim because Sight was not instantiated");
}
}
}
void FireBullet (){
}
Vector2 getPointInWorld (Vector3 point){
Vector2 pos = Camera.main.ScreenToWorldPoint(point);
return pos;
}
}
【问题讨论】:
-
有关游戏引擎的问题,请使用
unity3d标签而不是unity。 -
下次我会注意的,谢谢。
-
注意:我知道当 originPont 和 endPoint 相等时会出现错误。我更改了 if 语句并确认视线始终为空。
标签: unity3d rotation unityscript