[英]Unity3D - How to move objects in a Sine wave independantly?
In my game I have targets that spawn and move towards the player in a straight line. 在我的游戏中,我的目标会直线产生并朝玩家移动。 I use this code:
我使用以下代码:
transform.LookAt(target.transform);
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed);
Which makes the target home in on the player and move towards them. 这会使目标回到玩家身上并向他们移动。
I decided to try and make them move in a sin wave, so it looks less boring than going in a straight line, and I added a line of code, which now becomes: 我决定尝试使它们以正弦波运动,因此看起来比直线移动更无聊,我添加了一行代码,现在变成:
transform.LookAt(target.transform);
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed);
transform.position += transform.right * Mathf.Sin (Time.time * 3f) * 1f;
Now this works great, my enemies move left and right as they travel towards the player, except, they all follow the same path at the same time, resulting in a large group of targets moving left and right in a sort of choreographed way. 现在效果很好,我的敌人朝着玩家行进时会左右移动,除了它们都同时遵循相同的路径,从而导致大量目标以某种编排的方式左右移动。
I believe it is because I use Time.time
in the Mathf.Sin
piece of code, which results in all the targets using the same value to generate a sine wave. 我相信这是因为我使用
Time.time
在Mathf.Sin
一段代码,这导致使用相同的值,以产生一个正弦波的所有目标。
I've tried changing to Time.deltaTime
and changing the Time.time
variable to a Random.Range
variable between 2 numbers, but they either don't work, stop my targets from moving, or make them look like they are vibrating. 我尝试更改为
Time.deltaTime
并将Time.time
变量更改为2个数字之间的Random.Range
变量,但是它们要么不起作用,阻止我的目标移动,要么使它们看起来像在振动。 I've also tried using animations as well, but because of my MoveTowards
code, this doesn't work either. 我也尝试过使用动画,但是由于我的
MoveTowards
代码,这也不起作用。
So, is there a way to make a GameObject
move left and right in a sine wave and move forwards at the same time, but independently so they do not look choreographed? 那么,是否有一种方法可以使
GameObject
以正弦波的方式左右移动并同时向前移动,但又独立地移动,以使它们看起来没有编排? :-) :-)
In order to offset the phase of the sine function (while keeping the frequency and amplitude) you have to add a constant to x in sin(x). 为了补偿正弦函数的相位(同时保持频率和幅度),您必须在sin(x)中向x 添加一个常数。
So you could try transform.position += transform.right * Mathf.Sin (Time.time * 3f + i) * 1f;
因此,您可以尝试
transform.position += transform.right * Mathf.Sin (Time.time * 3f + i) * 1f;
where i is unique to the target moving towards the player. 我是唯一朝着玩家前进的目标。
See also: https://en.wikipedia.org/wiki/Sine_wave 另请参阅: https : //en.wikipedia.org/wiki/Sine_wave
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.