Easing trail with sine algorithms in Processing - algorithm

Here is my source code:
int index;
int num = 60;
float mx[] = new float[num];
float my[] = new float[num];
float explosion;
float x;
float y;
float px;
float py;
float xold;
float yold;
float xplode1;
float yplode1;
float xplode2;
float yplode2;
float xplode3;
float yplode3;
float xplode4;
float yplode4;
float easing = 0.05;
void setup() {
size(1366, 768);
noStroke();
// noFill();
fill(25, 155);
}
void draw() {
int which = frameCount % num;
explosion = explosion + 0.32;
background(92, 55, 169);
float targetX = mouseX;
float dx = targetX - px;
float lx = targetX - x;
if (abs(dx) > 1) {
mx[which] += dx * easing;
x += lx * easing;
if (mousePressed && (mouseButton == LEFT)) {
xplode1 = dx + 50 + sin(explosion)*30;
xplode2 = dx + 50 + sin(explosion)*30;
xplode3 = dx - 50 - sin(explosion)*30;
xplode4 = dx - 50 - sin(explosion)*30;
}
else {
xplode1 = -10;
xplode2 = -10;
xplode3 = -10;
xplode4 = -10;
}
}
float targetY = mouseY;
float dy = targetY - py;
float ly = targetY - y;
if (abs(dy) > 1) {
my[which] += dy * easing;
y += dy * easing;
if (mousePressed && (mouseButton == LEFT)) {
yplode1 = dy + 50 + sin(explosion)*30;
yplode2 = dy - 50 - sin(explosion)*30;
yplode3 = dy - 50 - sin(explosion)*30;
yplode4 = dy + 50 + sin(explosion)*30;
}
else {
yplode1 = -10;
yplode2 = -10;
yplode3 = -10;
yplode4 = -10;
}
}
for(int i = 0;i<num;i++){
index = (which + 1 + i) % num;
ellipse(mx[index], my[index], i, i);
}
ellipse(xplode1, yplode1, 10, 10);
ellipse(xplode2, yplode2, 10, 10);
ellipse(xplode3, yplode3, 10, 10);
ellipse(xplode4, yplode4, 10, 10);
}
I would like to have a trail of ~60 and also have some easing for the whole thing. I have got each feature working individually but when I added in the fading. There is quite alot of unneeded variables, I have not cleaned the code at all, I have been working on it for hours, I know there is probably a very simple solution that I just cannot see at the moment. Any help would be great, thanks.

Don't bite more than you can chew, learn the little things. Vectors will make your code much less messy. You can find a detailed description of the Vector class on the Processing site. In this way, instead of having two different variables xplode1 and xplode2, there will be one Vector object that stores both values. You may find those concepts difficult at first, but they'll be invalubale tools for future sketches.
If you feel comfortable with basic concepts such as variables, functions, conditionals and loops, start studying OOP (Object Oriented Programming). Again, Daniel Shiffman comes to help.
Also, be more specific when asking on StackOverflow. Solving a problem often means finding the right question.

Related

How do I make a variable randomly equal 1 of 2 numbers? (Processing)

I'm trying for the first time to make Pong. I don't always want the ball to go to the bottom right by adding 3 every single time. How would I make it so it will either do 3, or -3, but no number in between? I know that "||" doesn't work for integers, and "random(-3,3) has the chance of giving me numbers like "0.1" which wouldn't really function in here.
Code:
float circleX = 640/2;
float circleY = 360/2;
float xSpeed = 3;
float ySpeed = 3;
float Color = (255);
float circleHeight = 32;
float circleWidth = 32;
float xAcceleration = -1.0;
float yAcceleration = -1.0;
float paddleColor = 255;
float MyPaddleX = 630;
float OpPaddleX = 10;
float MyPaddleWidth = 10;
float OpPaddleWidth = -10;
void setup() {
size(640, 360);
frameRate(60);
}
void draw() {
background(0);
//Ball
fill(Color);
ellipse(circleX, circleY, circleWidth, circleHeight);
xSpeed = //(WHAT TO PUT HERE?)
circleX = circleX + xSpeed;
circleY = circleY + ySpeed;
//My Paddle
fill(paddleColor);
rect(MyPaddleX,mouseY,MyPaddleWidth,100);
//Bouncing
if (circleX >= OpPaddleX && OpPaddleX + OpPaddleWidth >= circleX) {
xSpeed = xSpeed * xAcceleration;
}
// Top/Bottom Bouncing
if (circleY > height || circleY < 0) {
ySpeed = ySpeed * yAcceleration;
}
//My Paddle Bounceback
if (circleY >= mouseY && circleY <= mouseY + 100) {
if (circleX >= MyPaddleX && circleX <= MyPaddleX + 3)
xSpeed = xSpeed * xAcceleration;
}
//Opponent Paddle
fill(paddleColor);
rect(OpPaddleX,circleY - 50,OpPaddleWidth,100);
//if (circleX < OpPaddleX || circleX > MyPaddleX) {
// circleX = width/2;
// circleY = height/2;
// xSpeed = 0;
// ySpeed = 0;
//}
}
You can generate a number between 0 and 1 and then compare that generated number to 0.5 to "flip a coin" in your code.
Think about it this way: when you call random(1), you'll get a value between 0 and 1. Half of those values will be less than 0.5, the other half will be greater than (or equal to) 0.5.
So you can do something like this:
float x;
if(random(1) < .5){
x = -3;
}
else{
x = 3;
}
You could expand this to choose from more numbers using else if statements, or you could shorten it into a single line of code using the ternary operator:
float x = random(1) < .5 ? 3 : -3;

How to make an (moving) ellipse clickable? Processing

So I started learning processing since a week ago and I'm trying to get a moving ellipse clickable. I followed the processing API, but I can't figure it out. I removed all the code relating to the clickable ellipse because it was a mess.
In the section where I declare all my vars you can see me using:
int breedte = 600;
int hoogte = 600;
These are suppose to be:
int breedte = width;
int hoogte = height;
But for some reason the width and height don't output the width and height declared in:
size(600,600)
So what I'm asking is:
How can I make the (moving) ellipse clickable?
Why I can't use width and height on 'int hoogte' and 'int breedte'?
Thanks in advace.
Main file:
int x = 0;
int leftSide = 0;
int rightSide = width;
int bottomSide = height;
int totalHits = 0;
int totalMiss = 0;
boolean start = false;
int circelSize = 100;
int circelRings = 24;
int circelSpeed = 1;
int circelPositionY = 0;
int breedte = 600;
int hoogte = 600;
String[] buttonText = {"Start","Stop"};
String buttonTextActive = buttonText[0];
int[] buttonColor = {0,90};
int buttonColorActive = buttonColor[0];
int buttonHighlight = 50;
int buttonSize = 80;
int buttonY = breedte - (buttonSize /2);
int buttonX = hoogte / 2 - 40;
void setup() {
size(600, 600);
smooth();
noStroke();
}
void draw() {
if (start) {
circelPositionY = circelPositionY + circelSpeed;
drawCircel(circelPositionY);
if (circelPositionY == (width + circelSize)) {
circelPositionY = 0;
}
}
drawButton();
}
Events file:
void mousePressed() {
// Start or Stop button
if(mouseX > buttonX & mouseX < buttonX + buttonSize & mouseY > buttonY & mouseY < buttonY + (buttonSize / 2)){
if(start) {
start = false;
buttonColorActive = buttonColor[0];
buttonTextActive = buttonText[0];
println("Game stoped");
} else {
start = true;
buttonColorActive = buttonColor[1];
buttonTextActive = buttonText[1];
println("Game started");
}
}
//HERE SHOULD GO THE CLICKABLE ELLPISE
}
Functions file:
void drawCircel(int circelPositionY) {
background(204);
for (int i = 0; i < circelRings; i = i+1) {
int even = i % 2;
if (even == 0) {
fill(255,0,0);
ellipse(-(circelSize / 2) + circelPositionY, height / 2 - (circelSize / 2), circelSize - (i * (circelSize / circelRings)), circelSize - (i * (circelSize / circelRings)));
} else {
fill(255);
ellipse(-(circelSize / 2) + circelPositionY, height / 2 - (circelSize / 2), circelSize - (i * (circelSize / circelRings)), circelSize - (i * (circelSize / circelRings)));
}
}
}
void drawButton() {
fill(buttonColorActive);
rect(buttonX,buttonY, buttonSize, buttonSize / 2);
fill(255);
textAlign(CENTER, CENTER);
text(buttonTextActive, buttonX + (buttonSize / 2),buttonY + (buttonSize / 4));
}
In the future, please try to post a MCVE instead of a bunch of disconnected snippets or your whole project. Also please only ask one question per post.
To make your circle clickable, you're going to have to write code that checks whether the circle is being clicked. That's actually two separate checks. First you have to detect when the mouse is pressed. One way to do that is by defining a mousePressed() function:
void mousePressed(){
// mouse is pressed
}
Then you have to check whether the mouse is currently inside the circle. You can use the dist() function for that: if the distance between the mouse and the center of the circle is less than the radius of the circle, then the mouse is inside the circle. That might look like this:
void mousePressed(){
if(dist(mouseX, mouseY, circleX, circleY) < circleRadius){
// mouse is pressed inside the circle
}
}
Shameless self-promotion: I wrote a tutorial on collision detection in Processing, including point-circle collision, available here.
As for why you can't use width and height at the top of your sketch, that's because code at the top of your sketch is executed before the setup() function fires, and the width and height variables aren't set until after you call size() from the setup() function. So you have to move that code to after you call size().
If you have follow-up questions, please post an updated MCVE in a new question post, and we'll go from there. Good luck.
Processing does not provide an api for hit detection, so you need to implement this by yourself, which I think is a great learning exercise. You can explore the mathematics of an ellipse here.
But the general approach is to use a function like the one below to check that the point you clicked on was indeed inside the ellipse you provided.
boolean InsideEllipse(
float x, float y,
float xc, float yc,
float width, float height
) {
// First half the width and height to get the ellipse parameters
float a = width / 2;
float b = height / 2;
// Now calculate the deltas:
float xd = x - xc;
float yd = y - yd;
// Now the equation of an ellipse is given by
// x^2 / a ^ 2 + y^2 / b ^ 2 = 1
// So if we are inside the ellipse, we would expect the left hand
// side of this expression to be less than one
boolean inside = xd * xd / (a * a) + yd * yd / (b * b) <= 1.0
return inside
}

Processing PVector rotations

The issue is i got an array of PVectors placed around my main PVector which is in the middle. I want my array of PVectors to rotate around my main PVector based on a rotation variable. Is there any way to do this?
Right now I have this code but it does not rotate the PVectors, just places them farther away based on the rotation var.
class Box {
PVector location;
PVector[] points;
float rotation = random(360);
Box() {
location = new PVector(random(width), random(height));
points = new PVector[4];
for(a = 0; a < points.length; a ++) {
points[a] = new PVector(0,0);
}
}
void update() {
points[0].x = location.x + 10 * sin(rotation);
points[0].y = location.y + 10 * sin(rotation);
points[1].x = location.x + 10 * sin(rotation);
points[1].y = location.y - 10 * sin(rotation);
points[2].x = location.x - 10 * sin(rotation);
points[2].y = location.y + 10 * sin(rotation);
points[3].x = location.x - 10 * sin(rotation);
points[3].y = location.y - 10 * sin(rotation);
}
To rotate the vectors, you do need to use trig functions like sin and cos like you have in your code. However, your approach isn't really the best. Adding onto the existing (x,y) coordinates on each update isn't really feasible, since the number you have to add on is changing every time. It's easier just to overwrite and calculate new values for each update. The x and y coordinates for a given angle are given by the unit circle:
So, the x of a given PVector varies with cos(theta) and the y varies with sin(theta). Check the following code:
Box b;
void setup(){
size(300,300);
b = new Box();
}
void draw(){
background(255);
b.update(mouseX, mouseY);
b.display();
}
class Box {
PVector location;
PVector[] points;
float rotation;
float radius;
Box() {
location = new PVector(width/2,height/2);
points = new PVector[7];
rotation = 0;
radius = 50;
for(int i = 0; i < points.length; i ++) {
//this centers the points around (0,0), so you need to add in
//the box coordinates later on.
points[i] = new PVector(radius*cos(rotation + i*TWO_PI/points.length),
radius*sin(rotation + i*TWO_PI/points.length));
}
}
void update(int x, int y) {
location.set(x,y);
rotation += 0.08; // change for different rotation speeds.
for(int i = 0; i < points.length; i++){
points[i].set(radius*cos(rotation + i*TWO_PI/points.length),
radius*sin(rotation + i*TWO_PI/points.length));
}
}
void display(){
stroke(0);
for(int i = 0; i < points.length; i++){
//points are treated as offsets from the center point:
line(location.x,location.y,location.x+points[i].x,location.y+points[i].y);
ellipse(location.x+points[i].x,location.y+points[i].y,10,10);
}
}
}
For every update() call, it increments the rotation variable and calculates the new x and y values for each point in the array. You can change the speed and direction of rotation by changing 0.08 to bigger/smaller/positive/negative numbers.
To rotate a point around location:
double x = cos(rotation) * (point.x-location.x) - sin(rotation) * (point.y-location.y) + location.x;
double y = sin(rotation) * (point.x-location.x) + cos(rotation) * (point.y-location.y) + location.y;
point.x = x;
point.y = y;
See Rotate a point by an angle

Calculating the position of points in a circle

I'm having a bit of a mind blank on this at the moment.
I've got a problem where I need to calculate the position of points around a central point, assuming they're all equidistant from the center and from each other.
The number of points is variable so it's DrawCirclePoints(int x)
I'm sure there's a simple solution, but for the life of me, I just can't see it :)
Given a radius length r and an angle t in radians and a circle's center (h,k), you can calculate the coordinates of a point on the circumference as follows (this is pseudo-code, you'll have to adapt it to your language):
float x = r*cos(t) + h;
float y = r*sin(t) + k;
A point at angle theta on the circle whose centre is (x0,y0) and whose radius is r is (x0 + r cos theta, y0 + r sin theta). Now choose theta values evenly spaced between 0 and 2pi.
Here's a solution using C#:
void DrawCirclePoints(int points, double radius, Point center)
{
double slice = 2 * Math.PI / points;
for (int i = 0; i < points; i++)
{
double angle = slice * i;
int newX = (int)(center.X + radius * Math.Cos(angle));
int newY = (int)(center.Y + radius * Math.Sin(angle));
Point p = new Point(newX, newY);
Console.WriteLine(p);
}
}
Sample output from DrawCirclePoints(8, 10, new Point(0,0));:
{X=10,Y=0}
{X=7,Y=7}
{X=0,Y=10}
{X=-7,Y=7}
{X=-10,Y=0}
{X=-7,Y=-7}
{X=0,Y=-10}
{X=7,Y=-7}
Good luck!
Placing a number in a circular path
// variable
let number = 12; // how many number to be placed
let size = 260; // size of circle i.e. w = h = 260
let cx= size/2; // center of x(in a circle)
let cy = size/2; // center of y(in a circle)
let r = size/2; // radius of a circle
for(let i=1; i<=number; i++) {
let ang = i*(Math.PI/(number/2));
let left = cx + (r*Math.cos(ang));
let top = cy + (r*Math.sin(ang));
console.log("top: ", top, ", left: ", left);
}
Using one of the above answers as a base, here's the Java/Android example:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
RectF bounds = new RectF(canvas.getClipBounds());
float centerX = bounds.centerX();
float centerY = bounds.centerY();
float angleDeg = 90f;
float radius = 20f
float xPos = radius * (float)Math.cos(Math.toRadians(angleDeg)) + centerX;
float yPos = radius * (float)Math.sin(Math.toRadians(angleDeg)) + centerY;
//draw my point at xPos/yPos
}
For the sake of completion, what you describe as "position of points around a central point(assuming they're all equidistant from the center)" is nothing but "Polar Coordinates". And you are asking for way to Convert between polar and Cartesian coordinates which is given as x = r*cos(t), y = r*sin(t).
PHP Solution:
class point{
private $x = 0;
private $y = 0;
public function setX($xpos){
$this->x = $xpos;
}
public function setY($ypos){
$this->y = $ypos;
}
public function getX(){
return $this->x;
}
public function getY(){
return $this->y;
}
public function printX(){
echo $this->x;
}
public function printY(){
echo $this->y;
}
}
function drawCirclePoints($points, $radius, &$center){
$pointarray = array();
$slice = (2*pi())/$points;
for($i=0;$i<$points;$i++){
$angle = $slice*$i;
$newx = (int)($center->getX() + ($radius * cos($angle)));
$newy = (int)($center->getY() + ($radius * sin($angle)));
$point = new point();
$point->setX($newx);
$point->setY($newy);
array_push($pointarray,$point);
}
return $pointarray;
}
Here is how I found out a point on a circle with javascript, calculating the angle (degree) from the top of the circle.
const centreX = 50; // centre x of circle
const centreY = 50; // centre y of circle
const r = 20; // radius
const angleDeg = 45; // degree in angle from top
const radians = angleDeg * (Math.PI/180);
const pointY = centreY - (Math.cos(radians) * r); // specific point y on the circle for the angle
const pointX = centreX + (Math.sin(radians) * r); // specific point x on the circle for the angle
I had to do this on the web, so here's a coffeescript version of #scottyab's answer above:
points = 8
radius = 10
center = {x: 0, y: 0}
drawCirclePoints = (points, radius, center) ->
slice = 2 * Math.PI / points
for i in [0...points]
angle = slice * i
newX = center.x + radius * Math.cos(angle)
newY = center.y + radius * Math.sin(angle)
point = {x: newX, y: newY}
console.log point
drawCirclePoints(points, radius, center)
Here is an R version based on the #Pirijan answer above.
points <- 8
radius <- 10
center_x <- 5
center_y <- 5
drawCirclePoints <- function(points, radius, center_x, center_y) {
slice <- 2 * pi / points
angle <- slice * seq(0, points, by = 1)
newX <- center_x + radius * cos(angle)
newY <- center_y + radius * sin(angle)
plot(newX, newY)
}
drawCirclePoints(points, radius, center_x, center_y)
The angle between each of your points is going to be 2Pi/x so you can say that for points n= 0 to x-1 the angle from a defined 0 point is 2nPi/x.
Assuming your first point is at (r,0) (where r is the distance from the centre point) then the positions relative to the central point will be:
rCos(2nPi/x),rSin(2nPi/x)
Working Solution in Java:
import java.awt.event.*;
import java.awt.Robot;
public class CircleMouse {
/* circle stuff */
final static int RADIUS = 100;
final static int XSTART = 500;
final static int YSTART = 500;
final static int DELAYMS = 1;
final static int ROUNDS = 5;
public static void main(String args[]) {
long startT = System.currentTimeMillis();
Robot bot = null;
try {
bot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
int howMany = 360 * ROUNDS;
while (howMany > 0) {
int x = getX(howMany);
int y = getY(howMany);
bot.mouseMove(x, y);
bot.delay(DELAYMS);
System.out.println("x:" + x + " y:" + y);
howMany--;
}
long endT = System.currentTimeMillis();
System.out.println("Duration: " + (endT - startT));
}
/**
*
* #param angle
* in degree
* #return
*/
private static int getX(int angle) {
double radians = Math.toRadians(angle);
Double x = RADIUS * Math.cos(radians) + XSTART;
int result = x.intValue();
return result;
}
/**
*
* #param angle
* in degree
* #return
*/
private static int getY(int angle) {
double radians = Math.toRadians(angle);
Double y = RADIUS * Math.sin(radians) + YSTART;
int result = y.intValue();
return result;
}
}
Based on the answer above from Daniel, here's my take using Python3.
import numpy
def circlepoints(points,radius,center):
shape = []
slice = 2 * 3.14 / points
for i in range(points):
angle = slice * i
new_x = center[0] + radius*numpy.cos(angle)
new_y = center[1] + radius*numpy.sin(angle)
p = (new_x,new_y)
shape.append(p)
return shape
print(circlepoints(100,20,[0,0]))

Draw arrow on line algorithm

Does anyone have an algorithm for drawing an arrow in the middle of a given line. I have searched for google but haven't found any good implementation.
P.S. I really don't mind the language, but it would be great if it was Java, since it is the language I am using for this.
Thanks in advance.
Here's a function to draw an arrow with its head at a point p. You would set this to the midpoint of your line. dx and dy are the line direction, which is given by (x1 - x0, y1 - y0). This will give an arrow that is scaled to the line length. Normalize this direction if you want the arrow to always be the same size.
private static void DrawArrow(Graphics g, Pen pen, Point p, float dx, float dy)
{
const double cos = 0.866;
const double sin = 0.500;
PointF end1 = new PointF(
(float)(p.X + (dx * cos + dy * -sin)),
(float)(p.Y + (dx * sin + dy * cos)));
PointF end2 = new PointF(
(float)(p.X + (dx * cos + dy * sin)),
(float)(p.Y + (dx * -sin + dy * cos)));
g.DrawLine(pen, p, end1);
g.DrawLine(pen, p, end2);
}
Here's a method to add an arrow head to a line.
You just have to give it the coordinates of your arrow tip and tail.
private static void drawArrow(int tipX, int tailX, int tipY, int tailY, Graphics2D g)
{
int arrowLength = 7; //can be adjusted
int dx = tipX - tailX;
int dy = tipY - tailY;
double theta = Math.atan2(dy, dx);
double rad = Math.toRadians(35); //35 angle, can be adjusted
double x = tipX - arrowLength * Math.cos(theta + rad);
double y = tipY - arrowLength * Math.sin(theta + rad);
double phi2 = Math.toRadians(-35);//-35 angle, can be adjusted
double x2 = tipX - arrowLength * Math.cos(theta + phi2);
double y2 = tipY - arrowLength * Math.sin(theta + phi2);
int[] arrowYs = new int[3];
arrowYs[0] = tipY;
arrowYs[1] = (int) y;
arrowYs[2] = (int) y2;
int[] arrowXs = new int[3];
arrowXs[0] = tipX;
arrowXs[1] = (int) x;
arrowXs[2] = (int) x2;
g.fillPolygon(arrowXs, arrowYs, 3);
}

Resources