# My projects library #4! Gallery Megathread

**URL:** https://discourse.processing.org/t/my-projects-library-4-gallery-megathread/31103
**Category:** Gallery
**Created:** [July 7, 2021, 11:46am UTC](https://discourse.processing.org/t/my-projects-library-4-gallery-megathread/31103 "2021-07-07T11:46:48Z")
**Posts on this page:** 1
**Showing post:** 19

<div class="post-metadata">

### Author: ![CodeMasterX](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/codemasterx/32/2942_2.png) [@CodeMasterX](https://discourse.processing.org/u/CodeMasterX)
#### Post date: [August 27, 2021, 10:00am UTC](https://discourse.processing.org/t/my-projects-library-4-gallery-megathread/31103/19 "2021-08-27T10:00:24Z")

</div>

**#54 2D simple collisions demo 1**

This is a simple demo for a 2D collision detection with rectangles. The only square that can move is the player. If you find any bugs, do tell!

> **Code**
>
> ```auto
> int px = 10, py = 10, a = 20;
> int cx = 0, cy = 0, speed = 1;
> obstacle o = new obstacle(275, 275, 50, 50);
> void setup() {
> size(600, 600);
> }
> void draw() {
> background(0);
> movePlayer();
> fill(255);
> square(px, py, a);
> o.display();
> }
> void movePlayer() {
> for (int i = 0; i < speed; i++) {
> int nx = px+cx, ny = py+cy;
> if(collision(nx,py,a,a, o.x,o.y,o.s,o.s2) == false) px = nx;
> if(collision(px,ny,a,a, o.x,o.y,o.s,o.s2) == false) py = ny;
> }
> }
> void keyPressed() {
> char ky = (key+"").toLowerCase().charAt(0);
> if (ky == 'a') cx = -1;
> if (ky == 'd') cx = 1;
> if (ky == 'w') cy = -1;
> if (ky == 's') cy = 1;
> }
> void keyReleased() {
> char ky = (key+"").toLowerCase().charAt(0);
> if (ky == 'a' && cx == -1) cx = 0;
> if (ky == 'd' && cx == 1) cx = 0;
> if (ky == 'w' && cy == -1) cy = 0;
> if (ky == 's' && cy == 1) cy = 0;
> }
> boolean collision(int x1, int y1, int s1, int s12, int x2, int y2, int s2, int s22) {
> if (x1>x2-s1&&y1>y2-s12&& x1<x2+s2 && y1<y2+s22) return true; //x2-s1, y2-s12, x2+s2, y2+s22
> return false;
> }
> class obstacle {
> int x, y, s, s2;
> obstacle(int x_, int y_, int s_, int s2_) {
> x = x_;
> y = y_;
> s = s_;
> s2 = s2_;
> }
> void display() {
> fill(0, 0, 255);
> rect(x, y, s, s2);
> }
> }
> 
> ```

---

_[View the full topic](https://discourse.processing.org/t/my-projects-library-4-gallery-megathread/31103)._
