Joel Kleier's Electric Froth

up

Nim! pt4

by Joel Kleier on 2014-11-05


In my last post I went through my process of discovering how Nim works, at least a little bit. This time around I want to talk about what I did to get a circle bouncing back and forth on the screen! Not much of an acheivment, all things considered, but I spent most of my time just reading a little about SDL2_gfx.

First, I defined a type TBall to describe the position, size, and velocity of my little circle:

type
  TBall = object
    x: float
    y: float
    rad: float
    vx: float
    vy: float

Then, I instantiated what will become the bouncing circle:

var
  ball = TBall(
    x: 320,
    y: 240,
    rad: 10,
    vx: 100,
    vy: 0)

I do some checks to make sure the ball position is in bounds, and moving in the correct direction:

  ball.x += ball.vx * dt

  if ball.x < ball.rad:
    ball.x = ball.rad
    ball.vx *= -1
  elif ball.x > 640-ball.rad:
    ball.x = 640-ball.rad
    ball.vx *= -1

And finally, I render the ball with a handy method in the SDL2_gfx library:

 renderer.filledCircleRGBA(int16(ball.x), int16(ball.y), int16(ball.rad), 0,255,0,255)

The only tricky thing here is the type conversion — in nim there’s a distinct difference between type conversion and type casting.

Type conversion is used in a manner like int16(123.3), and the program will do it’s best to translate the value into the specified type.

Type casting is used in a manner like cast[int16](123.3), and the program will keep the same bit patter, but change the values type. Which will lead, inevitably to different values than conversion.

Until next time!