How to "teleport to the opposite side of the canvas when reaching the edge"?

edited November 2016 in Programming Questions

Hello.

I'm new here and I just started using p5.js (is it c alled p5.js? Or is it called Processing? What's the difference?) I'm sorry for the long title of this thread.

What I'm doing: I'm trying to create a Snake-like game. (You know, the player controls a "snake" that eats "food" and gets longer with each food eaten.) I have followed a youtube video for "getting started" with p5.js.

To the issue: When my snake reaches the edge of the canvas it either goes straight off the canvas and disappears (default behaviour), or is constrained by the canvas width/height (I am using the method called "constrain" for this.) However, I want the snake to teleport to the opposite side of the canvas (if it goes out toward the right side, I want it to reappear at the left side. Out up = reappear down below, etc.) I was wondering if there is a built-in way to do this in p5?

This is my current code:

this.posX=constrain(this.posX, 0, width-scl); this.posY=constrain(this.posY, 0, height-scl);

("this" being the snake-object, and posX and posY being it's current positon on the X- and Y-axis.)

Thanks in advance.

Answers

  • Answer ✓
    if (x > width) {
      x = 0;
    } else if (x < 0) {
      x = width;
    }
    

    etc

    it's tempting to use % in cases like this but % with -ve numbers will return a negative modulo, which isn't what you want. you can get around this but it looks slightly confusing:

    x = (x + width) % width; // untested
    
  • I tried this: x = (x + width) % width; // untested and it works fine.

    Thanks for the feedback. So there isn't any built-in (like a function/method) way of doing this, then?

  • % = % (modulo)

    See the: % (modulo) reference

    Note this is mathematically speaking a remainder operator; for negative numbers it does not strictly behave like modulo. If you are using positive numbers, this distinction doesn't matter.

    https://processing.org/reference/modulo.html

Sign In or Register to comment.