移动游戏对象在一个平滑的圆圈围绕玩家对象
本文关键字:对象 玩家 平滑 游戏 移动 一个 | 更新日期: 2023-09-27 18:10:44
如果有区别,我使用unity 5.1.2。
我有一个游戏对象盾牌,我想在玩家周围绕圈移动。我让它在一定程度上工作,盾牌对输入的反应很好,但不是动画,因为它只是传送到新的位置,而不是在一个平滑的旋转中绕圈移动。游戏是2D自上而下的,所以只能在x/y平面上工作。我试过使用lerp和slerp,但没有任何乐趣
将非常感谢您的帮助,以解决这个问题!
到目前为止我写的是:
public class ShieldMovement : MonoBehaviour {
public Transform target; //player shield is attaced to
float distance = 0.8f; // distance from player so it doesn't clip
Vector3 direction = Vector3.up;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float angle = Mathf.Atan2 (Input.GetAxisRaw("rightH"), Input.GetAxisRaw("rightV"))* Mathf.Rad2Deg;
if(Input.GetAxis("rightH") != 0f || Input.GetAxis("rightV") != 0f)
{
direction = new Vector3(Input.GetAxis("rightH"),Input.GetAxis("rightV"), 0.0f ) ;
}
Ray ray = new Ray(target.position, direction);
transform.position = ray.GetPoint(distance);
if(Input.GetAxis("rightH") != 0f || Input.GetAxis("rightV") != 0f)
{
transform.rotation = Quaternion.AngleAxis(angle,Vector3.forward*-1);
}
}
}
试试这个。有这么多对Input.GetAxis("...")
的方法调用,你真的想在开始的时候只调用它一次,然后把它缓存到一个变量来加快速度。你也不需要检查if(Input.GetAxis("rightH") != 0f || Input.GetAxis("rightV") != 0f)
两次,所以我把所有的东西都放在一张支票里。我加了一个Time.smoothDeltaTime
的乘法,希望能让你更顺利
float h = Input.GetAxis("rightH");
float v = Input.GetAxis("rightV");
float angle = Mathf.Atan2(h, v) * Mathf.Rad2Deg;
if(h != 0f || v != 0f)
{
float step = Time.smoothDeltatime * speed;
direction = Vector3.RotateTowards(transform.forward, new Vector2(h, v).normalized, step, 0.0F);
Ray2D ray = new Ray2D(target.position, direction);
transform.position = ray.GetPoint(distance);
transform.rotation = Quaternion.AngleAxis(angle, -Vector3.forward);
}
经过多次搜索和一些帮助,我终于解决了问题,谢谢大家:)这是我想出的解决方案
public class ShieldMovement : MonoBehaviour {
public Transform target; //player shield is attaced to
float distance = 0.8f; // distance from player so it doesn't clip
Vector3 direction = Vector3.up;
public float circSpeed = 0.1f; // Speed Shield moves around ship
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float rh = Input.GetAxisRaw("rightH");
float rv = Input.GetAxisRaw("rightV");
if(Mathf.Abs(rh) > 0.15f || Mathf.Abs(rv) > 0.15f)
{
Vector3 targetDir = new Vector3(rh, rv, 0.0f);
direction = Vector3.Slerp(transform.position-target.position, targetDir, circSpeed);
}
Ray ray = new Ray(target.position, direction); // cast ray in direction of point on circle shield is to go
transform.position = ray.GetPoint(distance); //move shield to the ray as far as the radius
float angleY = transform.position.y - target.position.y;
float angleX = -(transform.position.x - target.position.x);
float angle = Mathf.Atan2 (angleY, angleX) * Mathf.Rad2Deg-90; //Get angle
if(Mathf.Abs(rh) > 0.15f || Mathf.Abs(rv) > 0.15f)
{
transform.rotation = Quaternion.AngleAxis(angle,Vector3.forward*-1); // keep shield facing outwards in respect to player, will need revisiting on animating shield properly
}
}
}