Following a landscape (2D)

I know I ask a lot of stupid questions that have probably been answered before, but I never seem to find my answer.

Im trying to program an object to follow along the landscape that I made, Right now, the landscape is only in a picture. All I want is to have the object follow along the landscape and change the direction to be parallel with the ground as it goes. It doesn’t need to be overly complex as there wont be a situation where the object cannot go up or down, it is a basic landscape.

If you can at least provide a link to an old thread that is fine, as there probably is one. Search engines and I do not get along :\

If the landscape is a picture you have two options:

1 - Look at all the pixel values and do some sort of color comparison at any given X to find what the floor is at that position. i.e.


//Assume ground is a BufferedImage with type BufferedImage.TYPE_INT_ARGB
//Assume we have a ground color that is a 4 int array (might be like {0,0,0,0})
//x is the X position to check and startY is where the entity is standing (so you can make caves and the like work).
public int get groundHeightAtX(int x, int startY)
{
    int[] testArray = new int[4];
    for (int y = startY; y < ground.getData().getHeight(); y++)
    {
            int[] pixels = ground.getData().getPixel(x,y,testArray);
            if (pixels[0] == groundColor[0] && pixels[1] == groundColor[1] && pixels[2] == groundColor[2] && pixels[3] == groundColor[3])
            {
                return y;
            }
    }
    //If there's no floor found, this is considered a bottomless pit.
    return Integer.MAX_VALUE;
}

If you do that, it would be smart to cache the values for every X (in another array, probably) so that you’re not calling this constantly for every single entity.

2 - Create some sort of geometry that represents the ground, probably a bunch of points - you’d find which points that you lie between and then use the slope of the line to decide the height at that particular point. Faster but requires more effort.

You can evaluate the partial derivatives of the heightmap (the image) and get the gradient (dHeight/dx, dHeight/dy).

Since the image changes in steps, you have to interpolate these values first though before you can compute the gradient. You can use bilinear interpolation for this.

When you then have the gradient, you can choose to follow this vector forward (uphill), backward (downhill), or perhaps a vector that is perpendicular to it to stay at the same height.