(CGA) Objects and the Coordinate Grid Lesson

Objects and the Coordinate Grid

An expression is anything that has a type and a value. An expression can compute a value using literals, variables, constants and/or operators. Since most programs operate primarily on numbers, the most commonly used operators are often those that perform arithmetic operations.

There are many mathematical and logic operators used in expressions to change values during program execution.

Movement on the Coordinate Grid

Changing an Actor's Location

To change an objects location, use the setLocation method. Before you can change a location, you need to know the current location of the object. Use the getX() and getY() method in the Actor class to get the objects current location. Then you can change it by adding or subtracting to make the object move up, down, right or left.

Using Variables to Move an Actor

setLocation(getX(), getY() + 1);       Moves an object down

setLocation(getX(), getY() - 1);        Moves an object up

setLocation(getX() + 1, getY());       Moves an object right

setLocation(getX() - 1, getY());        Moves an object left

Using Width or Height of the Actor Object

You can also use the width or height of an object to set the location.  

setLocation(getX() - getWidth() - 50,     getY());

setLocation(getX(),   getY()   - getHeight - 50);

Using the Width or Height of the Actor Object's Image

You can use the width or height of an image to set the location.  You need to use the getImage() method first to get the image, then use you get the width.

Use dot notation to separate the two methods.  

setLocation(getX() - getImage().getWidth(),  getY());

setLocation(getX(),  getY() - getImage().getHeight());

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION