Constrain mouse daw to 45degrees Processing - processing

How does one constrain interactively drawing a line to 45degrees?
Imagine there in an underlining grid that's at 45 degees which the mouse draw is magnetized too. Perhaps on mousedown decides which your starting position is and after that your Mouse.X and Mouse.Y position only update in 45 degrees from that starting click?
float dif = 10;
float easing = 0.05;
boolean current = false;
boolean started = false;
float rainbow, x, y;
float colbase;
PVector pos, prev_pos, update_pos;
float step = 25;
void setup(){
size(400, 400);
background(100);
colorMode(HSB);
}
void draw(){
if (rainbow >= 255) rainbow=0; else rainbow+=5;
if (frameCount % dif == 0) {
colbase = rainbow;
}
if(mousePressed){
update_pos();
if(current){
started = true;//start drawing
pos = update_pos;
}else{
prev_pos = update_pos;
}
current = !current;
}else{
update_pos();
started = false;
pos = update_pos;
prev_pos = update_pos;
}
if(started){
//style for lines
strokeWeight(step);
stroke(colbase,255,255);
noFill();
line(prev_pos.x, prev_pos.y, pos.x, pos.y);
}
}
PVector update_pos(){
x = lerp(x, mouseX, easing);
y = lerp(y, mouseY, easing);
update_pos = new PVector(x, y);
return update_pos;
}

I would like to say that I like this. Also, that this question was ultimately way harder to answer than I though it would be.
Here's the result:
First, I took the liberty to reorganize your example code. I don't know how experienced you are, and maybe some of the things I changed were on purpose, but it seemed to me that your example had a lot of weird code bits dangling. Here's the example code with my changes (check the next code block for the answer, this one is more like a code review to help you in general):
float dif = 10;
float easing = 0.05;
boolean current, started; // automatically initializing as false unless stated otherwise
float rainbow;
float colbase;
PVector pos, prev_pos;
float step = 25;
void setup() {
size(400, 400);
background(100);
colorMode(HSB); // clever!
pos = prev_pos = new PVector(); // instanciating some non-null PVectors
}
void draw() {
pos = prev_pos = update_pos(); // cascade attribution: it starts by the last one and goes back toward 'pos'
if (mousePressed) {
if (!started) {
// initializing variables needed for drawing
started = true;
pos = prev_pos = new PVector(mouseX, mouseY);
}
} else {
started = false;
}
if (started) {
updateColor();
strokeWeight(step);
stroke(colbase, 255, 255);
noFill();
line(prev_pos.x, prev_pos.y, pos.x, pos.y);
}
}
void updateColor() {
if (rainbow >= 255) {
rainbow=0;
} else {
rainbow+=5;
}
if (frameCount % dif == 0) {
colbase = rainbow;
}
}
PVector update_pos() {
float x = lerp(pos.x, mouseX, easing);
float y = lerp(pos.y, mouseY, easing);
return new PVector(x, y);
}
Notice how I changed a couple variables names. As a general rule, you should always name your variables as if the guy maintaining your code was an angry biker who knows where you live.
Now to solve your actual question:
boolean isDrawing;
float rainbow, colbase, dif, easing, step, centerZone;
PVector pos, prev_pos, origin, quadrant;
void setup() {
size(400, 400);
background(100);
colorMode(HSB); // clever!
centerZone = 5; // determine how close to the original click you must be to change quadrant
dif = 10;
easing = 0.05;
step = 25;
origin = pos = prev_pos = new PVector();
}
void draw() {
updatePosition();
if (mousePressed) {
if (!isDrawing) {
// setting variables needed for drawing
isDrawing = true;
origin = pos = prev_pos = new PVector(mouseX, mouseY); // drawing should always start where the mouse currently is
}
} else {
isDrawing = false;
}
if (isDrawing) {
updateColor();
strokeWeight(step);
stroke(colbase, 255, 255);
noFill();
line(prev_pos.x, prev_pos.y, pos.x, pos.y);
}
}
void updateColor() {
if (rainbow >= 255) {
rainbow=0;
} else {
rainbow+=5;
}
if (frameCount % dif == 0) {
colbase = rainbow;
}
}
void updatePosition() {
float relativeX = pos.x - origin.x;
float relativeY = pos.y - origin.y;
float diffX = mouseX - origin.x;
float diffY = mouseY - origin.y;
float distance = abs(diffX) > abs(diffY) ? abs(diffX) : abs(diffY); // this is just inline if, the syntax being " condition ? return if true : return if false; "
prev_pos = pos;
// validating if the mouse is in the same quadrant as the pencil
PVector mouseQuadrant = new PVector(diffX > 0 ? 1 : -1, diffY > 0 ? 1 : -1);
// we can only change quadrant when near the center
float distanceFromTheCenter = abs(relativeX) + abs(relativeY);
if (quadrant == null || distanceFromTheCenter < centerZone) {
quadrant = new PVector(diffX > 0 ? 1 : -1, diffY > 0 ? 1 : -1);
}
// if the mouse left it's quadrant, then draw toward the center until close enough to change direction
// ^ is the XOR operator, which returns true only when one of the sides is different than the other (one true, one false)
// if the quadrant info is positive and the diff coordinate is negative (or the other way around) we know the mouse has changed quadrant
if (distanceFromTheCenter > centerZone && (relativeX > 0 ^ mouseQuadrant.x > 0 || relativeY > 0 ^ mouseQuadrant.y > 0)) {
// going toward origin
pos = new PVector(lerp(prev_pos.x, origin.x, easing), lerp(prev_pos.y, origin.y, easing));
} else {
// drawing normally
pos = new PVector(lerp(prev_pos.x, origin.x + (distance * quadrant.x), easing), lerp(prev_pos.y, origin.y + (distance * quadrant.y), easing));
}
}
I'll answer your questions on this code if you have any. Have fun!
EDIT:
This part could use more explainations, so let's elaborate a little bit:
if (distanceFromTheCenter > centerZone && (relativeX > 0 ^ mouseQuadrant.x > 0 || relativeY > 0 ^ mouseQuadrant.y > 0)) {
// going toward origin
} else {
// drawing normally
}
The point of this check is to know if the mouse is still in the same quadrant than the "pencil", by which I mean the point where we're drawing.
But what are the "quadrants"? Remember, the user can only draw in 45 degrees lines. Theses lines are defines in relation to the point where the user clicked to draw, which I call "origin":
Which means that the screen is always divided into 4 different "quadrants". Why? Because there is 4 different directions where we can draw. But we don't want the user to have to stick to these exact pixels to be able to draw, do we? We could, but that's not how the algo is working: it poses a pencil on the page and then follows the mouse. So here if the mouse goes up-left from origin, the pencil will draw on the up-left branch of the 45 degrees X lines. Each of these imaginary lines has it's own "part of the screen" where they control where the pencil has the right to draw, which I call "quadrants":
Now with this algorithm we can force the pencil over the 45 degrees lines, but what happens if the mouse goes from one quadrant to another one? I figured out that the pencil should follow, but without breaking the "only drawing in 45 degrees lines" rule, so it has to go through the center before changing quadrant:
There is no big secret here. It's kind of easy to figure the business rules we want to apply:
While the mouse and the pencil are in the same quadrant, follow the mouse's position to draw (but only on the line).
If the mouse is in a different quadrant from the pencil, draw toward the center, then toward the mouse normally.
Which is exactly what we're doing here:
if (mouse and pencil are in different quadrants) {
// draw toward origin
} else {
// draw toward the mouse
}
Then... if it's so simple, why this convoluted code?
(distanceFromTheCenter > centerZone && (relativeX > 0 ^ mouseQuadrant.x > 0 || relativeY > 0 ^ mouseQuadrant.y > 0))
Well, really, it could be written in a waaay easier to read way, but it would be longer. Let's decompose it and see why it's written this way:
My operational logic here go as follow:
As you probably know, point (0,0) is on the upper-left side of the sketch. Most drawing in computer science calculate coordinates this way.
Quadrants exist in relation to the origin point (where the user clicked to start drawing).
Relative coordinates in each quadrant will be either positive or negative. X will be positive if they are to the right of origin. Y will be positive if they are lower in the screen than origin:
If you follow my logic, when relative coordinate of the mouse and pencil aren't both positive or both negative in the same way, it would mean that they are not located in the same quadrant.
So:
distanceFromTheCenter > centerZone => when we're close enough to the center, we can let the pencil switch direction. No need to calculate the rest if the pencil isn't near the center.
relativeX > 0 ^ mouseQuadrant.x > 0 => relativeX is really just pos.x - origin.x. It's where the pencil is in relation to origin. mouseQuadrant "knows" where the mouse is in relation to the origin (it's just diffX and diffY as interpreted for later use, in fact we totally could have used diffX and diffY instead as we just compare if they are positive or negative numbers)
Why the XOR operator if it's so simple? Because of this:
relativeX > 0 ^ mouseQuadrant.x > 0
// is the same thing than this pseudocode:
if (relativeX sign is different than mousequadrant.x's sign)
// and the same thing than this more elaborated code:
!(relativeX > 0 && mouseQuadrant.x > 0) || !(relativeX < 0 && mouseQuadrant.x < 0)
// or, in a better writing:
(relativeX > 0 && mouseQuadrant.x < 0) || (relativeX < 0 && mouseQuadrant.x > 0)
...which is also convoluted and also ugly. So, really, (relativeX > 0 ^ mouseQuadrant.x > 0 || relativeY > 0 ^ mouseQuadrant.y > 0) is just a short hand for:
(!(relativeX > 0 && mouseQuadrant.x > 0) || !(relativeX < 0 && mouseQuadrant.x < 0) || !(relativeY > 0 && mouseQuadrant.y > 0) || !(relativeY < 0 && mouseQuadrant.y < 0))
I hope this just made sense! Have fun!

Related

Creating random pixeled lines in Proccesing

I'm trying to make a game and I'm stuck on random level design. Basically, I'm trying to create a line from one edge/corner to another edge/corner while having some randomness to it.
See below image 1 [link broken] and 2 for examples. I'm doing this in processing and every attempt I've tried hasn't yielded proper results. I can get them to populate randomly but not in a line or from edge to edge. I'm trying to do this on a 16 x 16 grid by the way. Any ideas or help would be greatly appreciated thanks!
Image 2:
Based on your description, the challenge is in having a connected line from top to bottom with a bit of randomness driving left/right direction.
There are multiple options.
Here's a basic idea that comes to mind:
pick a starting x position: left's say right down the middle
for each row from 0 to 15 (for 16 px level)
pick a random between 3 numbers:
if it's the 1st go left (x decrements)
if it's the 2nd go right (x increments)
if it's the 3rd: ignore: it means the line will go straight down for this iteration
Here's a basic sketch that illustrates this using PImage to visualise the data:
void setup(){
size(160, 160);
noSmooth();
int levelSize = 16;
PImage level = createImage(levelSize, levelSize, RGB);
level.loadPixels();
java.util.Arrays.fill(level.pixels, color(255));
int x = levelSize / 2;
for(int y = 0 ; y < levelSize; y++){
int randomDirection = (int)random(3);
if(randomDirection == 1) x--;
if(randomDirection == 2) x++;
// if randomDirection is 0 ignore as we don't change x -> just go down
// constrain to valid pixel
x = constrain(x, 0, levelSize - 1);
// render dot
level.pixels[x + y * levelSize] = color(0);
}
level.updatePixels();
// render result;
image(level, 0, 0, width, height);
fill(127);
text("click to reset", 10, 15);
}
// hacky reset
void draw(){}
void mousePressed(){
setup();
}
The logic is be pretty plain above, but free to replace random(3) with other options (perhaps throwing dice to determine direction or exploring other psuedo-random number generators (PRNGs) such as randomGaussian(), noise() (and related functions), etc.)
Here's a p5.js version of the above:
let levelSize = 16;
let numBlocks = levelSize * levelSize;
let level = new Array(numBlocks);
function setup() {
createCanvas(320, 320);
level.fill(0);
let x = floor(levelSize / 2);
for(let y = 0 ; y < levelSize; y++){
let randomDirection = floor(random(3));
if(randomDirection === 1) x--;
if(randomDirection === 2) x++;
// if randomDirection is 0 ignore as we don't change x -> just go down
// constrain to valid pixel
x = constrain(x, 0, levelSize - 1);
// render dot
level[x + y * levelSize] = 1;
}
// optional: print to console
// prettyPrintLevel(level, levelSize, numBlocks);
}
function draw() {
background(255);
// visualise
for(let i = 0 ; i < numBlocks; i++){
let x = i % levelSize;
let y = floor(i / levelSize);
fill(level[i] == 1 ? color(0) : color(255));
rect(x * 20, y * 20, 20, 20);
}
}
function prettyPrintLevel(level, levelSize, numBlocks){
for(let i = 0; i < numBlocks; i+= levelSize){
print(level.slice(i, i + levelSize));
}
}
function mousePressed(){
setup();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>
The data is a structured a 1D array in both examples, however, if it makes it easier it could easily be a 2D array. At this stage of development, whatever is the simplest, most readable option is the way to go.

Translating horizontally inverted quads

A couple of days ago I asked a question about translations and rotations in Processing.
I wanted to:
translate, invert and rotate a single quadrilateral (PShape object) multiple times
then change the height of one of its 2 top vertices
so as the whole thing act as an articulated arm that can be bent either to the right or the left.
Thanks to the help of #Rabbid76 I was able to achieve this effect but I am now facing another issue when translating the last 5 top horizontally inverted quads.
When bending the object, the first 3 quads get separated from the last 5 and. And the more the bending leg is curved, the farther they get apart.
I would really appreciate if someone could help me fix the translation part (from line 65 to 68) so as the quads stay attached to each other to matter how strong the bending is.
Any suggestion regarding that matter would be also greatly appreciated.
SCRIPT
int W = 40;
int H = 40;
int nQuads = 8;
int xOffset = 27;
float[] p0 = {-W/2 + xOffset, -H/2};
float[] p1 = {-W/2, H/2};
float[] p2 = {W/2, H/2};
float[] p3 = {W/2, -H/2};
PShape object;
void setup(){
size(600, 600, P2D);
smooth(8);
}
void draw(){
background(255);
// Bending to the left
float bending = sin(frameCount*.05) * .1;
p0[1] -= bending;
pushMatrix();
translate(width/2, height/2);
float minX = min( min(p0[0], p3[0]), min(p2[0], p1[0]) );
float maxX = max( max(p0[0], p3[0]), max(p2[0], p1[0]) );
float cptX = (minX+maxX)/2;
//Rotation Angle
float angle = atan2(p3[1]-p0[1], p3[0]-p0[0]);
//Pivot Height
float PH = p0[1] + (p3[1]-p0[1]) * (cptX-p0[0])/(p3[0]-p0[0]);
for (int i = 0; i < nQuads; i++){
float PivotHeight = (i % 2 == 1) ? PH : H/2;
//Height translation
if (i > 0){
translate(0, PivotHeight);
}
//Rotate once every 2 quads
if (i%2 == 1){
rotate(angle*2);
}
//Height translation
//Flip all quads except 1st one
if (i > 0){
translate(0, PivotHeight);
scale(1, -1);
}
//NOT working --> Flipping horizontally the last 5 top QUADS
if (i == 3){
scale(-1, 1);
translate(- xOffset, 0); //trying to align the quads on the X axis. Y translation is missing
rotate(-angle*2);
}
object();
}
popMatrix();
}
void object() {
beginShape(QUADS);
vertex(p0[0], p0[1]);
vertex(p1[0], p1[1]);
vertex(p2[0], p2[1]);
vertex(p3[0], p3[1]);
endShape();
}
Just providing a workaround to my own question but won't accept it as a valid answer as I don't really understand what I'm doing and it's probably not the most efficient solution.
int W = 40;
int H = 40;
int nQuads = 8;
int xOffset = 27;
float[] p0 = {-W/2 + xOffset, -H/2};
float[] p1 = {-W/2, H/2};
float[] p2 = {W/2, H/2};
float[] p3 = {W/2, -H/2};
PShape object;
void setup(){
size(600, 600, P2D);
smooth(8);
}
void draw(){
background(255);
// Bending to the left
float bending = sin(frameCount*.05) * .3;
p0[1] -= bending;
pushMatrix();
translate(width/2, height/2);
float minX = min( min(p0[0], p3[0]), min(p2[0], p1[0]) );
float maxX = max( max(p0[0], p3[0]), max(p2[0], p1[0]) );
float cptX = (minX+maxX)/2;
//Rotation Angle
float angle = atan2(p3[1]-p0[1], p3[0]-p0[0]);
//Pivot Height
float PH = p0[1] + (p3[1]-p0[1]) * (cptX-p0[0])/(p3[0]-p0[0]);
for (int i = 0; i < nQuads; i++){
float PivotHeight = (i % 2 == 1) ? PH : H/2;
//Height translation
if (i > 0){
translate(0, PivotHeight);
}
//Rotate once every 2 quads
if (i%2 == 1){
rotate(angle*2);
}
//Height translation
//Flip all quads except 1st one
if (i > 0){
translate(0, PivotHeight);
scale(1, -1);
}
//Flipping horizontally the last 5 top QUADS
if (i == 3){
scale(-1, 1);
translate(0, PivotHeight);
rotate(-angle*2);
translate(0, PivotHeight);
translate(-xOffset , H/2 - p0[1]);
}
object();
}
popMatrix();
}
void object() {
beginShape(QUADS);
vertex(p0[0], p0[1]);
vertex(p1[0], p1[1]);
vertex(p2[0], p2[1]);
vertex(p3[0], p3[1]);
endShape();
}

Processing: collisions with trails

Dealing with collisions in Processing is straightforward. However, how do I identify collisions with trails?
Example: imagine the light cycles in Tron, if you wish, with the alteration that trails of derezzed light cycles do not disappear. In Tron, if a cycle intersects any point another cycle, itself included, has ever been, it 'dies'. How do I efficiently find this event in Processing?
One hacky workaround is to draw the line into a PImage and check if the colour at a location is the same as the background or not (e.g. a pre-existing line, hence a collision).
Here's a rough (and slightly inefficient (due to get()/set() calls) proof of concept:
PImage buffer;
//how mutch we scale down = how pixely this will look
int multiplier = 8;
//scaled down width/height
int w,h;
//cursor position
int px,py;
//cursor velocity;
int vx,vy;
void setup(){
size(400,400);
noSmooth();
w = width / multiplier;
h = height / multiplier;
buffer = createImage(w,h,RGB);
clear();
}
void clear(){
java.util.Arrays.fill(buffer.pixels,color(0));
buffer.updatePixels();
}
void draw(){
//update cursor
px += vx;
py += vy;
//check edges
if(px < 0){
px = w-1;
}
if(px > w){
px = 0;
}
if(py < 0){
py = h-1;
}
if(py > h){
py = 0;
}
//check collision
if(keyPressed){
if(keyCode == UP || keyCode == DOWN || keyCode == LEFT || keyCode == RIGHT){
checkSelfIntersection();
}
}
//paint cursor
buffer.set(px,py,color(0,192,0));
//render on screen
image(buffer,0,0,width,height);
}
void checkSelfIntersection(){
//if the pixel ahead is not the same colour as the background
if(buffer.get(px+vx,py+vy) > color(0)){
clear();
println("Cycle go BOOM!");
}
}
void keyPressed(){
if(keyCode == UP){
vy = -1;
}
if(keyCode == DOWN){
vy = +1;
}
if(keyCode == LEFT){
vx = -1;
}
if(keyCode == RIGHT){
vx = +1;
}
}
void keyReleased(){
vx = vy = 0;
}
A similar concept can be done be keeping track of points in a list and checking if a new point is already part of this list (collision) or not:
ArrayList<PVector> path = new ArrayList<PVector>();
//cursor position
int px,py;
//cursor velocity;
int vx,vy;
void setup(){
size(400,400);
noFill();
strokeWeight(10);
}
void draw(){
//update cursor
px += vx;
py += vy;
//check edges
if(px < 0){
px = 0;
}
if(px > width){
px = width;
}
if(py < 0){
py = 0;
}
if(py > height){
py = height;
}
//check collision
if(keyPressed){
if(keyCode == UP || keyCode == DOWN || keyCode == LEFT || keyCode == RIGHT){
checkSelfIntersection();
}
}
background(255);
beginShape();
for(int i = 0 ; i < path.size(); i++){
PVector p = path.get(i);
vertex(p.x,p.y);
}
endShape();
}
void checkSelfIntersection(){
PVector cursor = new PVector(px,py);
if(path.contains(cursor)){
path.clear();
println("Cycle go BOOM!");
}else{
path.add(cursor);
}
}
void keyPressed(){
if(keyCode == UP){
vy = -5;
}
if(keyCode == DOWN){
vy = +5;
}
if(keyCode == LEFT){
vx = -5;
}
if(keyCode == RIGHT){
vx = +5;
}
}
void keyReleased(){
vx = vy = 0;
}
The concept isn't that different from how games like Snake/Volfied/etc. check for self intersections.
Note I'm cheating a bit by updating a "cursor" on keys with a small velocity: this avoid gaps in the lines. If you try to replace with the mouse, you'll notice the collision check may fail if the mouse moves fast as it checks one point against a list of recorded points. An alternative might be to split the list of points into pairs of lines and check if the new point intersects any of them.
You might want to also check this similar question
Stack Overflow isn't really designed for general "how do I do this" type questions. It's for specific "I tried X, expected Y, but got Z instead" type questions. That being said, I'll try to help in a general sense.
You can probably just keep track of the lines formed by the cycles, in the form of an ArrayList of all of the points where a player turned. Then at each step, you can check whether the player is intersecting with any of those lines.
More specifically, you'd probably want to form another line between the previous player coordinate and the next player coordinate. Then check whether that line intersects with any of the other lines using formulas that I'm sure you can find through a google search or two.
You probably don't have to do anything smarter than that unless you're talking about very very large playing fields (as in, millions of lines). So it's a little early to ask about efficiency.
There are of course many other ways to approach the problem. You might also use a 2D array that keeps track of the trails, or you could use pixel-based collision, or probably any number of other solutions. The point is you need to try something and post a MCVE along with a specific question if you get stuck, and we'll go from there. Good luck.

Need to rotate and move images in processing?

I am fast approaching several deadlines for my highschool graduation project so any advice you can give would be great. My project is to code a movie. The idea is to use processing to move the characters like tokens and also use code to animate things like rain and fire. Right now I am finding it very difficult to move images and/or rotate them. This is a big hurtle for my project. The current code I have for this is butchered and complicated but here it is.
Image of leading lady, Radial: https://www.dropbox.com/s/x3gvendnaeftapj/radialoutlinel.png
/*
Radialrolling
*/
PImage img; // Declare variable "a" of type PImage
float ballX = 10;
float ballY = 200;
float h = 300;
//create a variable for speed
float speedY = 2; // spped set to 0 in order to test rotating. Necessary for rolling motion
float speedX = 0.;
void setup() {
size(800,800);
smooth();
noStroke();
background(0, 0, 0);// Load the image into the program
// change the mode we draw circles so they are
// aligned in the top left
ellipseMode(CORNER);
img = loadImage("radialoutlinel.png");
}
void RadialRoll(){
rotate(0);//if this is anything but 0 ball will appear of screen
image(img, ballX, ballY, h, h); //create a continuos rotation using the new fun
//nctions in the draw things
}
void draw() {
//clear the background and set the fill colour
background(0);
fill(255);
//draw the circle in it's current position
// ellipse(ballX, ballY, h,h);
//add a little gravity to the speed
speedY = speedY + 0;
speedX = speedX + .02;
ballX = ballX + speedX;
RadialRoll();
if (ballX > width - h) {
// set the position to be on the floor
ballX = width - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedX = speedX * -1;
//switch the direction
//speedY = speedY;
}
if (ballX > width - h) {
// set the position to be on the floor
ballX = width - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedX = speedX * -1;
//switch the direction
//speedY = speedY;
}
else if (ballX <= 0) {
// if the ball hits the top,
// make it bounce off
speedX = -speedX;
}
if (ballY > height - h) {
// set the position to be on the floor
ballY = height - h;
// and make the y speed 90% of what it was,
// but in the opposite direction
speedY = speedY * -1;
//switch the direction
//speedY = speedY;
}
else if (ballY <= 0) {
// if the ball hits the top,
// make it bounce off
speedY = -speedY;
}
}
How can I move images on screen and rotate them with little hassle?
Thank you very much.
-TheIronHobo
First when you look at rotate() function it take radians (values from 0 to TWO_PI) as argument so when you want fluent rotation use something like this
rotate(counter*TWO_PI/360);
Where counter could be integer value increased in every draw() loop. But if you just add this to you code image will be rotating around point [0,0] (upper left corner) and you will not see image for 1/4 of the rotation. To better understanding this you should read this TUTORIAL then you could start with basic rotation:
PImage img;
int counter = 1;
void setup() {
size(800, 800);
smooth();
background(0, 0, 0);
img = loadImage("radialoutlinel.png");
imageMode(CENTER); //you can change mode to CORNER to see the difference.
}
void draw() {
background(0);
fill(255);
counter++;
translate(width/2, height/2);
rotate(counter*TWO_PI/360);
image(img, 0, 0, 300, 300);
}
Then if you want also move image from left to right side you will just adjust translate() first parameter.

Breakout (the game) in Processing

So, I am creating the game breakout in processing (programming language) but can't quite figure out a function to check for collision against the bat.
So far the section I have written for collision against the bat only collides the ball against the base and returns it in the opposite direction. For now, the game is a never ending phenomenon where the ball just collides with the walls. What I am trying to do is, collide the ball against the bat.
Oh this is my homework, so just please point me in the right direction instead of doing it for me.
Here's the code:
// Basic Breakout game
// Code from Matthre Yee-King
// brick position
float brickX;
float brickY;
// brick width and height
float brickH;
float brickW;
// ball position
float ballX;
float ballY;
// ball diameter
float ballD;
// ball direction
float ballDx;
float ballDy;
// bat position
float batX;
//bat width
float batW;
float batH;
//bat colour
float batB;
void setup() {
size (500, 500, P2D);
// set sizes of game items
brickW = 100;
brickH = 50;
batW = 100;
batH = 25;
ballD = 25;
batB = 255;
// random brick position
brickX = random(0, width - brickW);
brickY = random (0, height / 2);
// bat in the centre
batX = (width/2) - (batW/2);
// ball atop bat
ballX = batX + (batW/2);
ballY = height - batH - (ballD/2);
// ball movement
ballDx = random(-5, 5);
ballDy = -5;
rectMode(CORNER);
ellipseMode(CENTER);
}
void draw() {
// check for ball collision
// with top or sides of bat
checkBallAgainstBat();
// check for ball collision with
// left right and top walls
// and bounce
checkBallAgainstWalls();
// check ball against brick
checkBallAgainstBrick();
// move the ball
ballX += ballDx;
ballY += ballDy;
background(0);
// draw the bat
fill(0, 255, 0);
rect(batX, height - batH, batW, batH);
// draw the brick
fill(0, 0, batB);
batB = (batB + 10) % 255;
rect(brickX, brickY, brickW, brickH);
// draw the ball
fill(255, 0, 0);
ellipse(ballX, ballY, ballD, ballD);
if (keyCode == 37) { // left cursor key
batX -= 10;
// keep it on the screen
if (batX < 0) {
batX = 0;
}
}
if (keyCode == 39) {
batX += 10;
if (batX > (width - batW)) {
batX = width - batW;
}
}
}
// when they let go of the key, reset the keyCode
void keyReleased() {
keyCode = -1;
}
// this function checks if the ball has hit the top or sides of the bat and
// updates its direction as appropriate so the ball bouncs off the bat
void checkBallAgainstBat() {
if (ballY + ballD > height - batH) {
ballDy *= -1;
}
}
// this function checks if the ball has hit the brick. It should bounce off
// the brick and return true if so
boolean checkBallAgainstBrick() {
return false;
}
// this function checks if the ball has hit the top, left or right
// walls and update its
// direction as appropriate so the ball bounces off the walls
void checkBallAgainstWalls() {
if (ballX + ballD > width) {
ballDx *= -1;
}
if (ballX - ballD < 0) {
ballDx *= -1;
}
if (ballY - ballD < 0) {
ballDy *= -1;
}
}
Since the bat in breakout is a fixed width, your collision detection can be quite simple (in pseudo-code):
if (lower_edge(ball) > top_edge(bat)) {
// the ball has entered territory where it might have collided
if ((left_edge(ball) <= right_edge(bat)) && (right_edge(ball) >= left_edge(bat))) {
// the ball's within the horizontal bounds of the bat, so it's a "hit"
... calculate deflection ...
} else {
// oops, ball's gone past the bat and wasn't hit
strike_out();
} else {
// ball's still above the bat somewhere. do nothing
}
In english: If the ball's lower edge has gone past where the top edge of the bat is, we've POSSIBLY got a collision. This is only checking the vertical axis of the play field. You then check if the left or right edges of the ball fall within the horizontal location of the bat. If neither side of the ball overlaps the bat, then you've lost. Otherwise you've collided and you do the collision detection.

Resources