Abhirajshri Winsome
Abhirajshri Winsome

Reputation: 175

If object rotated, other objects vanishing! p5.js

I'm a beginner in p5.js. This is my code till now:

function setup() {
  createCanvas(600, 600);
}

function draw() {
 background(50, 168, 82);
 road();
 sidepath();
 truck();
 house();
 tree();
}

function road() {
 fill(66, 62, 61);
 noStroke();
 rect(200, 0, 220, 600);

 fill(197, 222, 202);
 rect(300, 50, 40, 70);
 rect(300, 200, 40, 70);
 rect(300, 350, 40, 70);
 rect(300, 500, 40, 70);
}

function sidepath() {
 fill(67, 230, 80);
 rect(0, 0, 220, 600);
 rect(400, 0, 220, 600);
}

function house() {
 fill(245, 225, 110);
 rect(80, 50, 55, 55, 3);
 triangle(80, 50, 45, 80, 80, 105);

 fill(67, 230, 80);
 rect(92, 60, 30, 30); 
 fill(245, 225, 110);
 translate(width/6, height/120);
 rotate(PI/3.5);
 rect(5, 45, 13, 64, 3);
 translate(width/5, height/90);
 rotate(PI/2.4);
 rect(60, 63, 13, 64, 3);
}

function tree() {
 fill(78, 150, 84);
 triangle(70, 420, 30, 450, 70, 480);
 triangle(100, 410, 50, 450, 100, 490);
 triangle(130, 400, 75, 450, 130, 500);
 rect(130, 430, 38, 30);
}

Even if I put the tree, it doesn't appear because I've used rotate in my house. If you comment on the rotating part, the tree appears. Can I, however, get both of them?

Upvotes: 4

Views: 365

Answers (2)

Rabbid76
Rabbid76

Reputation: 211278

Operations like rotate() and translate() define a new transformation matrix and multiply the current matrix with the new matrix.
If you only want to apply a rotation to 1 object, you must save the current matrix with push before specifying the rotation, and restore the matrix with pop after you have driven the object.

Pseudo code:

push()
roatate(...)

// [...] draw object (e.g. rect())

pop()

Upvotes: 2

user15302406
user15302406

Reputation: 132

The problem is that your calling functions such as rotate() and translate(), without a push() or a pop() to store that data. The rotate() and translate also rotate and translate the tree because those two functions affect everything after it's called. The way to fix this is using push() and pop() I would recommend learning about these functions first because they are very useful.

 function house() {
 fill(245, 225, 110);
 rect(80, 50, 55, 55, 3);
 triangle(80, 50, 45, 80, 80, 105);

 fill(67, 230, 80);
 rect(92, 60, 30, 30); 
 fill(245, 225, 110);
push();
 translate(width/6, height/120);
 rotate(PI/3.5);
 rect(5, 45, 13, 64, 3);
 translate(width/5, height/90);
 rotate(PI/2.4);
 rect(60, 63, 13, 64, 3);
pop();
}

I've simply just added in a push() and a pop() so the rotate and translate only affect the house. I would recommend reading this page and reading this page They should sum up what push() and pop() do.

If you have any questions, I'd be glad to clarify.

Upvotes: 0

Related Questions