How do I make text grow then shrink while still keeping the same midpoint? - processing

I'm making a bit of a late father's day present. I need some sort of ____Mode(CENTER) for text. I am trying to make a piece of text expand, then shrink, then expand again, then shrink again, on a loop. However, what I attempt seems to grow and shrink sparatically, making the text move around, and not staying centered. Is there an easy way to do this with text?
Code:
String msg = "Happy Father's Day";
int ts = 50;
float textX = 165;
float textY = 312.5;
float tSize = 50;
boolean flip;
void setup() {
size(800, 600);
}
void draw() {
background(0);
fill(255);
textSize(tSize);
text(msg, textX, textY);
if (flip == false) {
tSize += 0.5;
textX -= 1;
textY -= 1;
} else if (flip == true) {
tSize -= 0.5;
textX += 1;
textY += 1;
}
if (tSize == 35) flip = false;
else if (tSize == 65) flip = true;
}

Rather than constantly modifying textX and textY, you can use textAlign if you want to keep the text centered. In this case, you can simply drop those 2 variables:
String msg = "Happy Father's Day";
int ts = 50;
float tSize = 50;
boolean flip;
void setup() {
size(800, 600);
textAlign(CENTER,CENTER);
}
void draw() {
background(0);
fill(255);
textSize(tSize);
text(msg, width/2, height/2);
if (!flip) {
tSize += 0.5;
} else {
tSize -= 0.5;
}
if (tSize == 35) flip = false;
if (tSize == 65) flip = true;
}
You can streamline your code by making flip a number which is always 1 or -1 rather than a Boolean. This reduces the amount of conditional logic required. Note also how the following code replaced the equality comparisons (==) with inequalities (<= and >=). Something like tSize == 65 does work with steps of size 0.5 (since 0.5 has a finite base-2 expansion) but if you changed 0.5 to e.g. 0.1 to try to make it slower, the value 65 would be skipped over entirely due to floating-point round-off error. Since tSize is declared to be a float, using == with it is asking for trouble.
String msg = "Happy Father's Day";
int ts = 50;
float tSize = 50;
float flip = -1;
void setup() {
size(800, 600);
textAlign(CENTER,CENTER);
}
void draw() {
background(0);
fill(255);
textSize(tSize);
text(msg, width/2, height/2);
tSize += flip * 0.5;
if (tSize <= 35 || tSize >= 65 ) flip *= -1;
}

Related

How can you write an algorithm to properly fill a circle using lines from the center?

Currently I try to write code for calculating the parts of the screen you can see and those who can't because of objects that block light in 2d, like in Among Us:
The code should run on a processor with very low specs (at least in 2020), the C64. On such a simple CPU it's not possible to do such complex math fast enough for a game, so I came up with an idea: First of all, I make everything tile based, that makes processing easier and also means that I can just change entire characters or their color cells. Then I just write code for the PC in Processing (that's a coding language similar to Java but easier to use) to calculate how rays of light would move (the following graphic should make that more understandable), first just with a rectangle (and a single quadrant):
Then I wrote some completely messy assembler code for using the recorded coordinates to just keep filling the tiles with an inverted character based on the number of the ray currently being drawn on the ray until they hit an object (/ the tile it wants to fill is not inverted and not a space) and then just go to the next ray. I reduced the radius to 7 so it just takes up 256 bytes, useful for ASM. And that totally worked, I was able to fix every single bug and the result was quite impressive, since I needed to add pause statements or everything ran so fast that you couldn't see anything.
After that worked, I tried it with a circle, setting the points using this code:
int pointNum = ceil(radius * PI * 2); // calculates the circumference
for(int i = 0;i < pointNum;i++){
float angle = map(i, 0, pointNum, 0, PI*2);
setPixel(sin(angle) * radius, cos(angle) * radius);
}
I previously used the Bresenham circle algorithm but that didn't quite work so I tried a more simple way. So ...
All the marked black tiles never get hit by any light, which is a pretty big issue, because it wouldn't make much sense in a game that you just can't see those tiles. The code I used, written in Processing, is:
float[] xPoints = new float[0];
float[] yPoints = new float[0];
float[] xPointsT;
float[] yPointsT;
float[] xPointsHad = new float[0];
float[] yPointsHad = new float[0];
int pos = 0;
float interpolPos = 0;
int radius = 12;
float tileSize = 800.0 / (2*radius+1);
String output = " !byte ";
int pointNum = ceil(radius * PI * 2);
void setup() {
size(800, 800);
frameRate(60);
xPointsT = new float[0];
yPointsT = new float[0];
/*for(int i = 0;i <= radius;i++){
setPixel(radius, i);
setPixel(i, radius);
}*/ //Uncomment this and comment the next 4 lines to get the rectangle version
for(int i = 0;i < pointNum;i++){
float angle = map(i, 0, pointNum, 0, PI*2);
setPixel(sin(angle) * radius, cos(angle) * radius);
}
xPoints = concat(xPoints, xPointsT);
yPoints = concat(yPoints, yPointsT);
}
void draw(){
if(interpolPos > radius){
pos++;
interpolPos = 0;
println(output);
output = " !byte ";
}
float x=0, y=0;
float interpolMul = interpolPos / radius;
x = xPoints[pos] * interpolMul;
y = yPoints[pos] * interpolMul;
interpolPos+=1;//sorta the resolution
background(0);
stroke(255);
for(int i = 0;i < 2*radius+1;i++){
for(int j = 0;j < 2*radius+1;j++){
if((round(x) + radius) == i && (round(y) + radius) == j){
fill(0, 255, 0);
if(output != " !byte ")
output += ", ";
output += i-radius;
output += ", ";
output += j-radius;
xPointsHad = append(xPointsHad, i);
yPointsHad = append(yPointsHad, j);
}
else{
int fillVal = 0;
for(int k = 0; k < xPoints.length;k++){
if(round(xPoints[k])+radius == i && round(yPoints[k])+radius == j){
fillVal += 64;
}
}
fill(0, 0, fillVal);
if(fillVal == 0){
for(int k = 0; k < xPointsHad.length;k++){
if(round(xPointsHad[k]) == i && round(yPointsHad[k]) == j){
fill(128, 0, 0);
}
}
}
}
rect(i * tileSize, j * tileSize, tileSize, tileSize);
}
}
strokeWeight(3);
stroke(0, 255, 255, 64);
for(int i = 0;i < xPoints.length;i++){
line((float(radius)+0.5) * tileSize, (float(radius)+0.5) * tileSize, (float(radius)+0.5+xPoints[i]) * tileSize, (float(radius)+0.5+yPoints[i]) * tileSize);
}
strokeWeight(1);
fill(255, 255, 0);
ellipse((x + radius + 0.5) * tileSize, (y + radius + 0.5) * tileSize, 10, 10);
}
void setPixel(float _x, float _y){
for(int i = 0; i < xPoints.length;i++){
if(_x == xPoints[i] && _y == yPoints[i]){
return;
}
}
for(int i = 0; i < xPointsT.length;i++){
if(_x == xPointsT[i] && _y == yPointsT[i]){
return;
}
}
xPointsT = append(xPointsT, _x);
yPointsT = append(yPointsT, _y);
}
(Instructions to get the rectangle are in the code)
Those mentioned tiles seem to be never hit because the rays on them just jump over them, but what can I do to prevent that? You can decrease interpolPos+=x; to hit more tiles because that way your steps are smaller, but that wastes quite some space, so I don't think that's a good solution. Ideally you could also just decrease the number of coordinates you draw to get a smaller vision. Has anyone a good idea how to do that?
You have chosen wrong method to find all touched cells - instead of point-based way you need cell(squares)-based approach - ray intersects rectangle rather than point.
There is article of Amanatides and Woo "A Fast Voxel Traversal Algorithm for Ray Tracing" for 2D.
Practical implementation.
Example:
Quick-made tracing example. Rays emitted from left top corner go to blue points. If ray meets black cell obstacle, it stops. Pink cells are lighted by rays, grey ones are not.
Okay, I found something that worked for me in my situation: I just used the part that totally works (the rectangle) and then just make that a circle by ignoring every tile hit that's further away from the light source then the radius + 0.5, because without + .5 the circle looks weird. You can try it yourself, here's the code:
float[] xPoints = new float[0];
float[] yPoints = new float[0];
float[] xPointsT;
float[] yPointsT;
float[] xPointsHad = new float[0];
float[] yPointsHad = new float[0];
int pos = 0;
float interpolPos = 0;
int radius = 7;
float tileSize = 800.0 / (2*radius+1);
int pointNum = ceil(radius * PI * 2);
String standardOutput = " !align 15,0\n !byte ";
void setup() {
size(800, 800);
frameRate(60);
xPointsT = new float[0];
yPointsT = new float[0];
for(int i = 0;i <= radius;i++){
setPixel(radius, i);
setPixel(i, radius);
} //Uncomment this and comment the next 4 lines to get the rectangle version
/*for(int i = 0;i < pointNum;i++){
float angle = map(i, 0, pointNum, 0, PI*2);
setPixel(sin(angle) * radius, cos(angle) * radius);
}*/
xPoints = concat(xPoints, xPointsT);
yPoints = concat(yPoints, yPointsT);
xPointsT = new float[0];
yPointsT = new float[0];
}
void draw(){
if(interpolPos > radius){
pos++;
interpolPos = 0;
String output = standardOutput;
for(int i = 0;i < radius + 1;i++){
int indexPos = floor(map(i, 0, radius + 1, 0, xPointsT.length));
output += round(xPointsT[indexPos]);
output += ",";
output += round(yPointsT[indexPos]);
if(i < radius){
output += ", ";
}
}
println(output);
xPointsT = new float[0];
yPointsT = new float[0];
}
float x=0, y=0;
float interpolMul = interpolPos / radius;
x = xPoints[pos] * interpolMul;
y = yPoints[pos] * interpolMul;
interpolPos+=1;//sorta the resolution
background(0);
stroke(255);
for(int i = 0;i < 2*radius+1;i++){
for(int j = 0;j < 2*radius+1;j++){
if((round(x) + radius) == i && (round(y) + radius) == j && sqrt(sq(round(x)) + sq(round(y))) < radius + 0.5){
fill(0, 255, 0);
xPointsT = append(xPointsT, i-radius);
yPointsT = append(yPointsT, j-radius);
xPointsHad = append(xPointsHad, i);
yPointsHad = append(yPointsHad, j);
}
else{
int fillVal = 0;
for(int k = 0; k < xPoints.length;k++){
if(round(xPoints[k])+radius == i && round(yPoints[k])+radius == j){
fillVal += 64;
}
}
fill(0, 0, fillVal);
if(fillVal == 0){
for(int k = 0; k < xPointsHad.length;k++){
if(round(xPointsHad[k]) == i && round(yPointsHad[k]) == j){
fill(128, 0, 0);
}
}
}
}
rect(i * tileSize, j * tileSize, tileSize, tileSize);
}
}
strokeWeight(3);
stroke(0, 255, 255, 64);
for(int i = 0;i < xPoints.length;i++){
line((float(radius)+0.5) * tileSize, (float(radius)+0.5) * tileSize, (float(radius)+0.5+xPoints[i]) * tileSize, (float(radius)+0.5+yPoints[i]) * tileSize);
}
strokeWeight(1);
fill(255, 255, 0);
ellipse((x + radius + 0.5) * tileSize, (y + radius + 0.5) * tileSize, 10, 10);
}
void setPixel(float _x, float _y){
for(int i = 0; i < xPoints.length;i++){
if(_x == xPoints[i] && _y == yPoints[i]){
return;
}
}
for(int i = 0; i < xPointsT.length;i++){
if(_x == xPointsT[i] && _y == yPointsT[i]){
return;
}
}
xPointsT = append(xPointsT, _x);
yPointsT = append(yPointsT, _y);
}
Besides the main difference to ignore tiles that are not in the circle, I also changed that I store the coordinates not in a String but in two arrays, because then I use code to stretch them when there are fewer then radius + 1 points, so I don't have to store multiple circles with different sizes in the C64's RAM, so it meets my main requirements: It should fill every tile and it should be downscalable by ignoring some points at the end of rays. And is if efficient? Uh ... there could be a better solution that fills the circle with fewer rays, but I don't care too much. Still, if you have an idea, it would be nice if you could tell me, but otherwise this question is solved.
Edit: I forgot to add a picture. Don't be confused, I modified the code after posting it so you can also see the blue tiles on the circle.

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();
}

Having trouble drawing Sierpinski's Triangle in Processing

I was trying to draw Sierpinski's Triangle in Processing 3, and managed to get it to run the first two layers. However, when it tries to draw the third and any later layers, it only draws more triangles in some of the triangles.
Here's the code
ArrayList<PVector> initPoints;
int level;
void setup() {
size(400, 400);
noFill();
initPoints = new ArrayList<PVector>();
initPoints.add(new PVector(width/2, height/4));
initPoints.add(new PVector(width/4, 3 * height/4));
initPoints.add(new PVector(3 * width/4, 3 * height/4));
}
void draw() {
triangle(initPoints.get(0).x, initPoints.get(0).y, initPoints.get(1).x, initPoints.get(1).y, initPoints.get(2).x, initPoints.get(2).y);
for (int i = 0; i < 3; i++) {
level = 1;
drawTri(i, initPoints, level);
}
}
PVector findMid(PVector a, PVector b) {
int midX = floor((a.x + b.x)/2);
int midY = floor((a.y + b.y)/2);
return new PVector(midX, midY);
}
void drawTri(int vertex, ArrayList<PVector> basePoints, int layer) {
level = layer + 1;
ArrayList<PVector> points = new ArrayList<PVector>();
points.add(basePoints.get(vertex % 3));
points.add(findMid(basePoints.get(vertex % 3), basePoints.get((vertex + 1) % 3)));
points.add(findMid(basePoints.get(vertex % 3), basePoints.get((vertex + 2) % 3)));
triangle(points.get(0).x, points.get(0).y, points.get(1).x, points.get(1).y, points.get(2).x, points.get(2).y);
if (level < 4) {
for (int i = 0; i < 3; i++) {
drawTri(i, points, level);
}
}
}
Any tips? I think it's something to do with how I'm running the for loops but I'm not sure.
Like I said in my comment, please try to debug your program before you post a question. You need to isolate the problem and understand exactly what the code is doing, and you can do that using print statements and the debugger that comes with the Processing editor.
But just looking at your code, I'm suspicious of the fact that you have a sketch-level level variable as well as a level variable that you're passing into the drawTri() function.
Think about the value of that sketch-level level variable as your code executes. Add print statements to see exactly what it's doing.
If I get rid of the sketch-level level variable, I get this, which I'm guessing is closer to what you wanted:
float x = int(random(0,1024));
float y = int(random(0,600));
float ax=512;
float ay=0;
float bx=0;
float by=600;
float cx=1024;
float cy=600;
void setup()
{
size(1024, 600);
background(0);
}
void nextPoint()
{
int r = int(random(1,7));
float X;
float Y;
if(r==1||r==2)
{
X = lerp(x, ax, 0.5) ;
Y= lerp(y, ay, 0.5);
}
else if(r==3||r==4)
{
X = lerp(x, bx, 0.5) ;
Y= lerp(y, by, 0.5);
}
else
{
X = lerp(x, cx, 0.5) ;
Y= lerp(y, cy, 0.5);
}
x=X;
y=Y;
}
void drawPoint()
{
colorMode(HSB,255,255,255);
stroke(map(y, 0, 15000,100,4000),200,255,10);
strokeWeight(1);
point(ax,ay);
point(bx,by);
point(cx,cy);
point(x, y);
}
void draw()
{
for(int i=0;i<100;++i)
{
drawPoint();
nextPoint();
}
}

modification in the animation of vertical lines with processing

i have modified the code for the animation of vertical lines which was given by . In the recent code I need to change the value between the two arrays of lines which are generated by the code and also make the disappearing of lines gradual. All the lines leaving or coming should have the same spacing between them. Below is the code.
//float[] linePositions = new float[10];
ArrayList<Integer> linePositions = new ArrayList<Integer>();
int lineWidth = 50;
int lineSpacing = 25;
int lineSpeed = 1;
int totalwidth;
int pixelperframe = 0;
int arraySize = 0;
void setup() {
size(640, 360);
println("Setup");
totalwidth = lineWidth+lineSpacing;
for (int i = 0; i < width; i=i +totalwidth) {
//Float value = 0 + (lineWidth+lineSpacing)*i;
linePositions.add(i);
}
arraySize = linePositions.size();
}
Boolean drawn = false;
void draw() {
println("Draw");
background(51);
//loop through the lines
//println("before Draw ka forloop"+linePositions.size());\
pixelperframe = ((lineSpeed - 10) > 1) ? (lineSpeed-10) : 1;
for (int i = 0; i < arraySize; i++) {
//println("Draw ka forloop");
rect(linePositions.get(i), 0, lineWidth, width);
int newPosition = linePositions.get(i) - pixelperframe ;
linePositions.set(i, newPosition);
//linePositions[i] -= lineSpeed;
//wrap the line
if ( linePositions.get(i) < 0) {
println("Wrapping the line");
linePositions.set(i, width);
// drawn = true;
}
}
//int temp = (width - linePositions.get(arraySize - 1)) - totalwidth;
//println(temp);
}
For the spacing between the lines to always be the same, you have to make sure that the total line spacing adds up to the total width of your screen. Right now each line takes up 75 pixels (50 for the line itself and 25 for the space after it), but your width is 640. That will always leave you with extra space, which will mess up your spacing after the lines start over.
So the easiest thing to do is to simply make your window a multiple of the line spacing. Let's go with 600, which is enough room for exactly 8 lines.
However, since you want your lines to slide off the screen, you actually need 9 lines, since you'll often see half of one line going off the screen while half of another line enters the screen. Draw some pictures to see exactly what I'm talking about
If I understand what you mean by making the lines "gradually" restart, you just have to restart them when their right side goes off the screen. In other words, when their x position is negative enough to be off the screen.
Putting it all together, it looks like this:
float[] linePositions = new float[9];
float lineWidth = 50;
float lineSpacing = 25;
float lineSpeed = 1;
void setup() {
size(600, 360);
for (int i = 0; i < linePositions.length; i++) {
linePositions[i] = (lineWidth+lineSpacing)*i;
}
}
void draw() {
background(51);
for (int i = 0; i < linePositions.length; i++) {
linePositions[i] -= lineSpeed;
rect(linePositions[i], 0, lineWidth, height);
if ( linePositions[i] < -(lineWidth+lineSpacing)) {
linePositions[i] = width;
}
}
}

animation of vertical bars using processing

I am basically trying to make a animation of vertical bars across the screen which should be equally spaced and continue until some key is pressed etc.. in the processing.org tool for animation.
I was able to get a kind of animation, but with hard coded values and had to write the same code again and again to generate the animation of bars for the whole frame/screen. I need to make it generic, so that changing the screen width or the size of the bars would not make me change the whole code but just the variables which control the parameters. Below is my code. I have written the code for three vertical bars but that needs to be done for the whole screen..
int a;
int i;
int j;
void setup() {
size(640, 360);
a = width/2;
i = 0;
}
void draw() {
background(51);
//need to avoid these repetitions each time for each bar
rect(a , 0, 25, width);
a = a - 1;
if (a < 0) {
a = width;
}
rect(i= a+50, 0, 25, width);
i = i - 1;
if (i < 0) {
i = width + a;
}
rect(j = i + 50, 0, 25, width);
j = j - 1;
if (a < 0) {
j = width + i;
}
}
It sounds like you're looking for an array.
An array is like a variable, only it can hold multiple values in its indexes. You can then use a for loop to iterate over the array and do stuff based on the values in the array.
Here's an example that uses an array to keep track of the line positions:
float[] linePositions = new float[10];
float lineWidth = 25;
float lineSpacing = 25;
float lineSpeed = 1;
void setup() {
size(640, 360);
for (int i = 0; i < linePositions.length; i++) {
linePositions[i] = width/2 + (lineWidth+lineSpacing)*i;
}
}
void draw() {
background(51);
//loop through the lines
for (int i = 0; i < linePositions.length; i++) {
//draw the line
rect(linePositions[i], 0, lineWidth, width);
//move the line
linePositions[i] -= lineSpeed;
//wrap the line
if ( linePositions[i] < 0) {
linePositions[i] = width;
}
}
}
More info on arrays can be found in the Processing reference.

Resources