Search code examples
androidopengl-es2dgame-physics

Tracking 2D objects on a path / pre-determined movement


I'm making an openGL top down space shooter type game to learn how to create a game. I have a lot of the basics down (game loop, logic isolation, etc).

One problem I'm encountering though is how to create more complicated object movement. I currently have some enemies moving in a sine wave down the screen. I'd like to have them perform more complicated movements, such as moving down the screen, stopping, then starting again and perhaps doing some loops in the process.

I've broken my movement logic out into it's own EnemyMovement interface that I can attach to any kind of enemy. Here's my sine wave movement class:

package com.zombor.shooter.movement;

import com.zombor.game.framework.math.Vector2;

public class Sine implements EnemyMovement
{
  private int direction;
  private float totalTime = 0;
  private float deltaTime;

  private int originalX;
  private int originalY;

  private float yVelocity = -4f;
  private float xVelocity = 0;

  public Sine(int x, int y)
  {
    direction = Math.random() > 0.5 ? 1 : -1;
    originalX = x;
    originalY = y;
  }

  public void setDeltaTime(float deltaTime)
  {
    this.deltaTime = deltaTime;
    totalTime+=deltaTime;
  }

  private float xVal()
  {
    return originalX + (float) Math.sin(Math.PI+totalTime)*2*direction;
  }

  public void setPosition(Vector2 position)
  {
    position.add(xVelocity * deltaTime, yVelocity * deltaTime);
    position.x = xVal();
  }
}

My objects have position, velocity and acceleration vectors.

Is there a commonly accepted way to do scripted movement?


Solution

  • A bezier curve is what I'm looking for.