unity3d - Unity 2D对象面方向其移动
问题描述
嘿伙计们,我无法让 2D 精灵面向它移动的方向。他们跟随地图上的航路点,我希望他们在通过航路点时旋转,但在实施时遇到了麻烦。如果您能帮上忙,我将不胜感激,谢谢。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointEnemy : MonoBehaviour
{
public float speed = 5f;
private Transform target;
private int wavepointIndex = 0;
private Rigidbody2D rigidBody;
bool points = false;
private void Start()
{
{
int random = (Random.Range(-10, 10));
if (random >= 0)
{
target = Waypoints.waypoints[0];
points = true;
} else {
target = Waypoints2.waypoints2[0];
}
}
}
void Update()
{
Vector2 dir = target.position - transform.position;
transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World);
if (Vector2.Distance(transform.position, target.position) <= 0.4f)
{
GetNextWaypoint();
}
}
void GetNextWaypoint()
{
if (points == false)
{
wavepointIndex++;
target = Waypoints.waypoints[wavepointIndex];
} else
{
wavepointIndex++;
target = Waypoints2.waypoints2[wavepointIndex];
}
}
}
解决方案
将以下函数添加到您的脚本并在 Update 中调用它
private void RotateTowardsTarget()
{
float rotationSpeed = 10f;
float offset = 90f;
Vector3 direction = target.position - transform.position;
direction.Normalize();
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle + offset, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}
如果旋转似乎关闭,只需将“偏移”值调整 90 倍,或者完全删除它。
推荐阅读
- javascript - Electron ipcMain / ipcRenderer 交付保证
- ruby-on-rails - Rails - 如何在同一操作中重定向、闪烁错误/通知和下载 csv?
- workbox - 如何从服务工作者向 Workbox 类实例的“消息”事件发送消息?
- typescript - NuxtJS Auth 错误与属性不存在
- c++ - 在 wndproc 和 MSG 中处理窗口消息,有什么区别?
- firebase - 如何使用 vue.js 和 firebase(目录结构)
- javascript - MaterializeCSS 中带有复选框的可折叠标题
- c - 使用 write() 将整数写入文件描述符?
- mysql - Mysql获取分组的两个表列的总和
- c# - C# Forms - 无法将文件从 Windows 资源管理器搜索拖到 RichTextBox