Aida E
Aida E

Reputation: 1100

move my Object with certain speed

consider a Car Object that should move forward in a road . I dont a have car object yet but I'll add that shape later . Instead of a car I have a square now how can I move it forward with specific speed?

any ideas?

here is my code

public class GLqueue {
private float vertices[] = { 1, 1, -1, // topfront
        1, -1, -1, // bofrontright
        -1, -1, -1, // botfrontleft
        -1, 1, -1, 
        1, 1, 1, 
        1, -1, 1, 
        -1, -1, 1, 
        -1, 1, 1,

};

private FloatBuffer vertBuff;
private short[] pIndex = { 3, 4, 0,  0, 4, 1,  3, 0, 1, 
        3, 7, 4,  7, 6, 4,  7, 3, 6, 
        3, 1, 2,  1, 6, 2,  6, 3, 2, 
        1, 4, 5,  5, 6, 1,  6, 5, 4,

};
private ShortBuffer pBuff;

public GLqueue() {

    ByteBuffer bBuff = ByteBuffer.allocateDirect(vertices.length * 4);
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff = bBuff.asFloatBuffer();
    vertBuff.put(vertices);
    vertBuff.position(0);

    ByteBuffer pbBuff = ByteBuffer.allocateDirect(pIndex.length * 4);
    pbBuff.order(ByteOrder.nativeOrder());
    pBuff = pbBuff.asShortBuffer();
    pBuff.put(pIndex);
    pBuff.position(0);

}

public void draw(GL10 gl) {
    gl.glFrontFace(GL10.GL_CW);
    gl.glEnable(GL10.GL_CULL_FACE);
    gl.glCullFace(GL10.GL_BACK);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertBuff);
    gl.glDrawElements(GL10.GL_TRIANGLES, pIndex.length,
            GL10.GL_UNSIGNED_SHORT, pBuff);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisable(GL10.GL_CULL_FACE);
}

}

Upvotes: 0

Views: 480

Answers (1)

Jave
Jave

Reputation: 31846

Velocity depends on two factors - time and distance: v = d/t.
'Moving' an object is usually done my changing the position relative to the starting position. This distance is calculated according to the above formula: d = vt.
This means that in order to know where to position our object when drawing we must know the velocity and the time.

The velocity is probably decided by the user or the program somehow (I.E the user pushes the button for driving faster and the velocity goes up). The current time can be retrieved by calling System.currentTimeMillis().

Here is a very simple example of an implementation:

//Variables:
long time1, time2, dt; 
float velocity; 
float direction;

//In game loop:

time1 = System.currentTimeMillis(); dt = time1-time2;

float ds = velocity*dt; //ds is the difference in position since last frame. car.updatePosition(ds, direction); //Some method that translates the car by ds in direction.

time2 = time1;

Upvotes: 1

Related Questions