I’m trying to create a top down shooting game where the enemy moves in sinusoidal motion. However when I use the following code, the enemy moves in sin wave at the center and doesn’t move left. If I remove the code for the sin wave, then the enemy moves left.
public float enemySpeed; float frequency = 5.0f; float magnitude = 0.8f; void FixedUpdate() { transform.position = transform.up * Mathf.Sin(Time.time * frequency) * magnitude; transform.Translate((enemySpeed* Vector2.left) * Time.deltaTime); }
public float enemySpeed;
float frequency = 5.0f;
float magnitude = 0.8f;
void FixedUpdate()
{
transform.position = transform.position + new Vector3(enemySpeed * Time.deltaTime, Mathf.Sin(Time.time * frequency) * magnitude, 0);
}
Problem is that you are setting a position to a single axis, and translation to a single axis. This will interfere with each other. First you focus on the up direction, then you focus on the left direction. I changed the code a little bit, and i got the object to move up and down and to the right, so you might want to add a - sign somewhere
Basically it’s just a simple equation, converting the x position of the object into a y position. This little snippet does what you want, and may be a little bit easier to understand:
using UnityEngine;
public class TestWave : MonoBehaviour
{
public float moveSpeed = 1f;
public float frequency = 1f;
public float amplitude = 1f;
void FixedUpdate()
{
float xPosition = transform.position.x;
float yPosition = Mathf.Sin(Mathf.PI * 2 * xPosition * frequency) * amplitude;
xPosition += moveSpeed * Time.deltaTime;
transform.position = new Vector3(xPosition, yPosition, transform.position.z);
}
}
It is ofcourse very similar to your own code, just a little bit more spread out.
The end result will not be that x moves a distance of 1 to left and right.