Hiilo
1
I’m working on a 2D game. I have enemy spawn points at all directions around the viewport. All the enemies will pass through the centre of the viewport. What I’m trying to do is make some enemies move in a sine wave. But the enemies could come from any spawn point. Here’s an image that hopefully will explain what I’m trying to do. Different colours mark some of the wished paths.
I have done some research but haven’t found a solution yet. The closest I came was the solution described here.
http://answers.unity3d.com/questions/305484/sine-movement.html That works fine
in one direction.
Here’s my current code
using UnityEngine;
using System.Collections;
public class SineMove : MonoBehaviour {
private GameObject center;
private Vector3 difference;
public float CurveSpeed = 5;
public float MoveSpeed = 0;
public float fTime = 2;
Vector3 vLastPos = Vector3.zero;
// Use this for initialization
void Start ()
{
center = GameObject.FindWithTag("CenterTarget");
difference = transform.position - center.transform.position;
}
// Update is called once per frame
void Update ()
{
fTime += Time.deltaTime * CurveSpeed;
Vector3 vSin = new Vector3(Mathf.Sin(fTime), -Mathf.Sin(fTime), 0);
Vector3 vLin = new Vector3(MoveSpeed, MoveSpeed, 0);
transform.position -= (vSin + vLin) * Time.deltaTime;
//Tried using difference but it didn't work
//transform.position -= (difference+vSin) *0.2f*Time.deltaTime;
//vLastPos Is only for Debug.Draw
vLastPos = transform.position;
Debug.DrawLine(vLastPos, transform.position, Color.green, 100);
}
}
Any help much appreciated.
What you have here is an issue with local space vs world space.
First of all, what I would suggest is to change from setting the position directly, to using transform.Translate and transform.Rotate.
- calculate the (vertical) sine wave movement in local space
- calculate the forward movement in local space
- create a vector3 based on the above
- use transform.Translate to apply the movement to the enemy
- use transform.Rotate to apply rotation of the enemy
Or just create a basic animation that plays when the enemy is charging in that direction. At least, that’s what I’d do.
If you’d like to do that, then go to Window or whatever at the top of Unity and click Animation. Very easy to learn, I learned it without even finding help, at least with making the Animation at least.
Hope that helps.