首先,我对编码总体上非常陌生,但我把它作为一种爱好,所以请原谅我普遍缺乏理解。
我正在组装一个侧面滚动的平台游戏,其中一个小角色跟随你,给你建议,点亮道路,填写传说等等。想想塞尔达传说中的Navi。我已经有了一个有效的脚本来跟踪玩家,我将在下面发布。
然而,我无法让它懒洋洋地漂浮在角色周围,而不是只是坐着不动。
public class WillOWispFollowPlayer : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.05f;
public Vector3 offset;
private void FixedUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
}
}
答案 0 :(得分:0)
我还没有涉足游戏开发,但我会如何实现它是对玩家或玩家附近的目标位置产生偏向的随机位置。
因此,假设在半间隔时间间隔内,您为同伴生成一个新的随机位置或方向,距离应该相对接近同伴当前位置。为了防止你的同伴随机飞离进入日落,你还应该确保这个随机位置或方向偏向于玩家位置,例如距离玩家越远,更偏向于向玩家迈进。
答案 1 :(得分:0)
在敲了一会儿之后,看着其他人的代码,这就是我想出来的。它为原始代码添加了两个函数。一种是具有可调加速和减速的随机方向功能,在FixedUpdate中应用。另一种是在单独的随机方向上的短暂速度爆发。效果比我原先预期的更加绚丽,并且不再是漂浮的漂移效果,但它有效。如果有人有任何想法让这种情绪变得更加紧张,更加流畅,浮动效果,我会接受建议。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class WillOWispFollowPlayer : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.05f;
public float smoothSpeedSlow = 0.02f;
public Vector3 offset;
public float hoverSpeed = 10000f;
public Rigidbody2D rb;
public static System.Timers.Timer hoverTimer;
public float acceleration;
public float deceleration;
private Rigidbody2D physics;
private Vector2 direction;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("HoverDirection", 0, 1); //calling the DoverDirection every second
physics = GetComponent<Rigidbody2D>();
physics.gravityScale = 0;
physics.drag = deceleration;
}
private void FixedUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
Vector3 smoothedPositionSlow = Vector3.Lerp(transform.position, desiredPosition, smoothSpeedSlow);
//setting up a "wander zone" where the Will'o'the'Wisp is less restricted within a defined distance of the player
if (Vector3.Distance((target.position + offset), this.transform.position) >= .5)
{
transform.position = smoothedPosition;
}
else
{
transform.position = smoothedPositionSlow;
}
//Random direction generator This results in a "flutter" effect
direction = UnityEngine.Random.insideUnitCircle;
Vector2 directionalForce = direction * acceleration;
physics.AddForce(directionalForce * Time.deltaTime, ForceMode2D.Impulse);
}
//A regular and prominant directional change, resulting in short darting motions around the target position
void HoverDirection()
{
rb.velocity = Random.onUnitSphere * hoverSpeed;
}
}