C# 如何连续自动将炮塔转向敌人方向?
我将一个炮塔作为游戏对象放置,我在inspector中将目标设置为敌人,但不知何故,炮塔只是指向我的敌人,但没有在z轴上持续旋转。有什么问题吗,有什么帮助吗 这是我的密码C# 如何连续自动将炮塔转向敌人方向?,c#,unity3d,angle,autorotate,C#,Unity3d,Angle,Autorotate,我将一个炮塔作为游戏对象放置,我在inspector中将目标设置为敌人,但不知何故,炮塔只是指向我的敌人,但没有在z轴上持续旋转。有什么问题吗,有什么帮助吗 这是我的密码 using UnityEngine; using System.Collections; public class TurretScript: MonoBehaviour { public Transform target; void Update() { Vector3 tarPos = new Vector
using UnityEngine;
using System.Collections;
public class TurretScript: MonoBehaviour
{
public Transform target;
void Update()
{
Vector3 tarPos = new Vector3(target.position.x, target.position.y, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(tarPos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
实现这一目标的最简单方法是什么?欺骗大概是这样的:
public class TurretScript: MonoBehaviour
{
//values that will be set in the Inspector
public Transform Target;
public float RotationSpeed;
void Update()
{
var direction = Target.transform.position - transform.position;
// Set Y the same to make the rotations turret-like:
direction.y = transform.position.y;
var rot = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rot,
RotationSpeed * Time.deltaTime);
}
}
您还可以从中使用Transform.LookAt
我发现这是最简单的方法,没有计算旋转的麻烦 你可能想把这篇文章发到,他们关注的是游戏开发的一般性问题和Unity的具体问题。它是旋转的,但不是圆形的,希望y轴和x轴是恒定的。itz根本不旋转:你设置了旋转速度吗?如果不是,你的旋转速度为零。也别忘了设定目标。我已经把转速设定为1Let我们。