Sponsored

Collapse

Announcement

Collapse
No announcement yet.

Placing Images - Swift Playgrounds

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Placing Images - Swift Playgrounds

    The goal of this lesson is to place a graphic in each quadrant of the universe.

    The coordinate system is divided by the x and y axes into four quarters, or quadrants, with the origin at the center, The coordinates in each quadrant have a different combination of positive and negative x, y values:

    (-x, y), (x,y)
    (-x, -y), (x, -y)

    Liven up Blu's universe with a few alien creatures, like the ones defined as graphics in the code.

    1. Place one graphic in each quadrant of the universe.

    2. Run your code and make sure the graphics end up where you expect.

    Hint: Sketch the x and y axes on paper to help you figure out the coordinates, Remember that x is the horizontal axis, and y the vertical, with (0,0) at the center. The coordinates in the four quadrants will each have a different combination of positive or negative x, y values, top right: (+,+), bottom right: (+, -), bottom left: (-, -), and top left: (-, +).

    Code:
    scene.clear()
    scene.backgroundImage = backgroundImage
    
    let blu = Graphic(image: bluImage)
    
    //Alien creatures
    let ghost = Graphic(image: ghostImage)
    let alien = Graphic(image: alienImage)
    let ogre = Graphic(image: ogreImage)
    let monster = Graphic(image: monsterImage)
    
    let theOrigin = Point(x: 0, y:0)
    scene.place(blu, at: theOrigin)
    
    // Place a graphic in each quadrant
    scene.place(ghost, at: Point(x: 250, y: 250))
    scene.place(alien, at: Point(x: -250, y: 250))
    scene.place(ogre, at: Point(x: 250, y: -250))
    scene.place(monster, at: Point(x: -250, y: -250))
    Good Work!

    What would your code be like if you had to place 10 objects no the scene, or even 30?! Notice how much code is repeated. Any time you see code repeated like this ask yourself, "is there a better way?"

    Think: Is there a more efficient way to do this using an array?

    Find out on the next lesson, which is "Placing an Array of Images".

  • #2
     

    Comment


    • #3
      Code:
      let creatures = [ghost, alien, ogre, monster]
      
      let quad1 = Point(x: 250, y: -250)
      
      let quad2 = Point(x: -250, y: 250)
      
      let quad3 = Point(x: 250, y: 250)
      
      let quad4 = Point(x: -250, y: -250)
      
      let quadrants = [quad1, quad2, quad3, quad4]
      
      // Place a graphic in each quadrant.
      
      let sequence = zip(creatures, quadrants)
      
      sequence.forEach { scene.place($0, at: $1) }
      Last edited by cxs2549; 01-11-2019, 10:15 AM.

      Comment

      Working...
      X