Moving heart using a constructor function - javascript

I'm trying to make a heart move left and right, using a constructor function. This is what I've got so far, for display
for(var a = 0; a < TWO_PI; a+=0.01){
this.r = this.x, 5;
this.b = this.r* 16 pow(sin(a), 3);
this.c = -this.r*(13* cos(a) - 5 * cos(2*a) -2*cos(3*a) - cos(4*a));
vertex(this.b, this.c);
}
all the var have been defined, but the image is only moving one line and add this.x to every line make the image not show, although the console is not saying anything. Can someone please help me?

Related

Rect Collisions

I am working on a game in Javascript in which I have a player try to collect coins. Both are currently rects() with different dimensions, and I am trying to incorporate a function that alerts the user when they have gotten a coin. Currently, this is my code for my player & coin collision detection.
isTouching(player) {
return player.x + player.width > this.x &&
this.x + this.width > player.x &&
player.y + player.height > this.y &&
this.y + this.height > player.y;
}
However, when I loop through my coins array and check for collisions, nothing happens. Why is this? Here is my code pertaining to this:
for (let x = 0; x < 5; x ++) { coins[x].collisions(); }
and...
collisions() {
if (this.isTouching(player)) {
alert("you got a coin!");
}
}
Both my coins and player have their own class, with my coins being stored in an array.
let player;
let coins = [];
player = new Player();
for (let x = 0; x < 5; x ++) { coins.push(new Coin()); }
Even when the player touches the coin, there is no alert. How can I fix this?
P.S. I know there are many libraries capable of checking for collisions between rectangles, but I wanted to utilize my own function to check for collisions. Please let me know how/if I need to change my collision detection system.
Also, if my provided code is unclear, here is a .zip (download linked) containing my program code: https://www.mediafire.com/file/00rz1ta5s55rvzf/game.zip/file
EDIT: A comment suggested I use a library to check for collisions, which I'm technically not allowed to do, but for the sake of testing, I tried it. I imported bmoren's p5.collide2D library which worked for me in the past, and used this code (below). However, the issue still remains, and the collisions between objects is not detected at all.
New code utilizing library:
if (this.touched()) {
alert("you got a coin!");
}
touched() {
return collideRectRect(this.x, this.y, this.width, this.height, player.x, player.y, player.width, player.height);
}
Just read all of your code. I was able to get the coin alert working, here's what you need to change
in game.engine.js, change the function setup. Here I have updated your loop, problem is your random x and y of coins need to be passed to your coin class instance.
function setup() {
// Apply classes to empty variables
console.log("Creating player...");
player = new Player();
console.log("Creating world...");
world = new World();
console.log("Creating coins...");
for (let i = 0; i < number_of_coins; i++) { coins.push(new Coin(coin_cords_X[i], coin_cords_Y[i])); }
console.log("Creating controller...");
controller = new Controller();
// Draw canvas with set size
console.log("Creating game screen...");
createCanvas(1250, 750);
}
Now, your game.coin.js, needs to take the passed x and y in the constructor and use it instead.
class Coin {
// Setup player attributes
x;
y;
width;
height;
constructor(x, y) {
this.x = x;
this.y = y;
this.width = 30;
this.height = 30;
}
show(x) {
fill(player.color);
rect(this.x, this.y, this.width, this.height);
}
// rest of the methods will be as is
}
Having done both of these things, it should work fine.
I am attaching the modified program zip.
https://www.mediafire.com/file/4krl9e0trdxlcx3/game.zip/file

Using an updating function, add an item to an array but it keeps updating whilst in there

I have been trying to fix this for about 2 hours now. I have tried many different methods but I can't get it to work.
I am making a snake game in JS (I'm learning it) and I am trying to add the positions of the snake to an array.
this.update = function() {
for (var i = 0; i < this.length - 1; i++) {
this.tail[i + 1] = this.tail[i];
}
this.tail[0] = createVector(this.position.x, this.position.y);
this.position.x += this.direction.x * 10;
this.position.y += this.direction.y * 10;
this.position.x = constrain(this.position.x, 0, width - 10);
this.position.y = constrain(this.position.y, 0, height - 10);
}
Once I add an item to the array, it continues to update the previous one. This is really annoying.
Imgur is down so here is a an image that is debug info. https://this.is-a-professional-domain.com/8c2801.png
I am using the p5 JS library which is why I am using "createVector", however the issue still happens when I don't use that method.

Mirroring right half of webcam image

I saw that you have helped David with his mirroring canvas problem before. Canvas - flip half the image
I have a similar problem and hope that maybe you could help me.
I want to apply the same mirror effect on my webcam-canvas, but instead of the left side, I want to take the RIGHT half of the image, flip it and apply it to the LEFT.
This is the code you've posted for David. It also works for my webcam cancas. Now I tried to change it, so that it works for the other side, but unfortunately I'm not able to get it.
for(var y = 0; y < height; y++) {
for(var x = 0; x < width / 2; x++) { // divide by 2 to only loop through the left half of the image.
var offset = ((width* y) + x) * 4; // Pixel origin
// Get pixel
var r = data[offset];
var g = data[offset + 1];
var b = data[offset + 2];
var a = data[offset + 3];
// Calculate how far to the right the mirrored pixel is
var mirrorOffset = (width - (x * 2)) * 4;
// Get set mirrored pixel's colours
data[offset + mirrorOffset] = r;
data[offset + 1 + mirrorOffset] = g;
data[offset + 2 + mirrorOffset] = b;
data[offset + 3 + mirrorOffset] = a;
}
}
Even if the accepted answer you're relying on uses imageData, there's absolutely no use for that.
Canvas allows, with drawImage and its transform (scale, rotate, translate), to perform many operations, one of them being to safely copy the canvas on itself.
Advantages is that it will be way easier AND way way faster than handling the image by its rgb components.
I'll let you read the code below, hopefully it's commented and clear enough.
The fiddle is here :
http://jsbin.com/betufeha/2/edit?js,output
One output example - i took also a mountain, a Canadian one :-) - :
Original :
Output :
html
<canvas id='cv'></canvas>
javascript
var mountain = new Image() ;
mountain.onload = drawMe;
mountain.src = 'http://www.hdwallpapers.in/walls/brooks_mountain_range_alaska-normal.jpg';
function drawMe() {
var cv=document.getElementById('cv');
// set the width/height same as image.
cv.width=mountain.width;
cv.height = mountain.height;
var ctx=cv.getContext('2d');
// first copy the whole image.
ctx.drawImage(mountain, 0, 0);
// save to avoid messing up context.
ctx.save();
// translate to the middle of the left part of the canvas = 1/4th of the image.
ctx.translate(cv.width/4, 0);
// flip the x coordinates to have a mirror effect
ctx.scale(-1,1);
// copy the right part on the left part.
ctx.drawImage(cv,
/*source */ cv.width/2,0,cv.width/2, cv.height,
/*destination*/ -cv.width/4, 0, cv.width/2, cv.height);
// restore context
ctx.restore();
}

JS randomize lineTo

I need to randomize the coordinates of shapes.
I know I need to somehow introduce the Math.floor(Math.Random * num); line in there, but nothing I do seems to work.
This is the block with the filled in coordinates I am trying to randomize.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.lineWidth="5";
ctx.strokeStyle="black";
ctx.moveTo;
ctx.lineTo(100,20);
ctx.lineTo(30,400);
ctx.lineTo(300,40);
ctx.lineTo(10,20);
ctx.stroke();
I've searched and searched and found nothing directly on this for some reason.
Sorry this is such a basic question too, I'm really new to this and still learning the basics.
Thank you in advance
Here is a fiddle showing the things I explain below.
Check this page for syntax regarding the Canvas.
If you want to be able to quickly and easily designate random coordinates, you can wrap it up in a function.
function randCoord(factor){
return Math.random() * factor;
}
and then use it like this:
// all of these will go to different points
ctx.moveTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
You could set a default scale:
function randCoord(factor){
if (factor == undefined){
factor = 100;
}
return Math.random() * factor;
}
Which would allow you to simply write the function name.
ctx.lineTo(randCoord(),randCoord());
You can also make another function that just adds a random additional point
function addRandomPoint(xFactor, yFactor) {
ctx.lineTo( randCoord(xFactor), randCoord(yFactor) );
}
// these will all add new points
addRandomPoint();
addRandomPoint();
addRandomPoint(200, 300);
addRandomPoint(-100, 25);
And then wrap it up in loop to make many points
// this will add 10 new points
for (var i = 0; i < 10; i++) {
addRandomPoint();
}
So you could do this:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.lineWidth="5";
ctx.strokeStyle="black";
ctx.moveTo(10, 10);
for (var i = 0; i < 10; i++) {
addRandomPoint();
}
ctx.stroke();

This is an infinite loop, but I cannot for the life of me figure out why

So pretty much I'm making a little web app to get better with using the canvas, but I'm stuck. I would like a rotating n-sided polygon (the drawing of lines already works). The game loop loops through a grid array (each point on the grid holds a subclass of a Point() object), and calls the tick() method on each. Everything works fine until it hits a ShapePoint() object (middle mouse to place on canvas). The ShapePoint's tick() method is somehow an infinite loop. If you put a console.log("hi") inside it, it will give you about 2000 "hi" messages, so it's working (in theory). The funny bit is, even though it is looping through stoke()'es, nothing is happening!
//################################################################
// THIS IS THE PROBLEM CLASS.
// So pretty much, when the game loop calls the tick() funciton
// of ANY ShapePoint object, everything hangs. The game is still
// looping through the ENTIRE tick() function (put console.log()
// functions in and you'll see what I mean) continually, but the
// effects it is supposed to display aren't shown.
//
//################################################################
function ShapePoint(x, y, sides) {
//position variable
this.positionOnCanvas = [x, y];
//number of sides
this.N = sides;
//current step
this.step = 0;
//the array to store all the angle data
this.thetas = new Array(this.N);
//the array to store all the vertex data
this.vertList = new Array(this.N);
//function to increase all the angels by an even amount
this.stepPoints = function(s) {
//for every side
for (i=0; i<this.N; i++) {
//multiply the current 'i' value by ((360/number of sides) + current step). This serves to create points at even intervals all the way around a circle, and have it increase by s every loop
this.thetas[i] = i*((360/this.N) + s);
//get the x value with 40*cos(angle for this point). Same for y, only with sin. Round both to 2 decimal places
this.vertList[i] = [Math.round((40*(Math.cos(this.thetas[i])))*100)/100, Math.round((40*(Math.sin(this.thetas[i])))*100)/100];
//if the current angle is between 90 and 180...
if (this.thetas[i]>=90 && this.thetas[i]<=180) {
//invert the x value
this.vertList[i][0] *= -1;
//else if the angle is between 180 and 270...
} else if (this.thetas[i]>=180 && this.thetas[i]<=270) {
//invert both the x and the y values
this.vertList[i][0] *= -1;
this.vertList[i][1] *= -1;
//else if the angle is between 270 and 360...
} else if (this.thetas[i]>=270 && this.thetas[i]<=360) {
//invert the y value
this.vertList[i][1] *= -1;
}
//nothing needed for 0-90 because both are positive
}
}
this.tick = function() { //<<<<<<<<THIS IS THE PROBLEM FUNCTION!
//setup all the points forward
this.stepPoints(this.step);
//for every side in this polyogn...
for (i=0; i<this.N; i++) {
//shorten the location of the positions
var posX = this.vertList[i][0] + this.positionOnCanvas[0];
var posY = this.vertList[i][1] + this.positionOnCanvas[1];
//begin drawing
ctx.beginPath();
//move to the x and y location of the current point
ctx.moveTo(posX, posY);
//if point is not the last in the array...
if (i < this.N-1) {
//draw a line to the next point in the array
ctx.lineTo(this.vertList[i+1][0] + this.positionOnCanvas[0], this.vertList[i+1][1] + this.positionOnCanvas[1]);
//else...
} else {
//draw a line to the first point in the array
ctx.lineTo(this.vertList[0][0] + this.positionOnCanvas[0], this.vertList[0][1] + this.positionOnCanvas[1]);
}
//draw a line
ctx.strokeStyle = "#000000";
ctx.lineWidth = 0.5;
//end
ctx.stroke();
//draw the vertex
ctx.fillStyle = "orange";
ctx.fillRect(posX-2, posY-2, 4, 4);
}
//draw the origin of the polygon
ctx.fillStyle = "lightPurple";
ctx.fillRect(this.positionOnCanvas[0]-2, this.positionOnCanvas[1]-2, 4, 4);
//if the step is greater than 360, set it to 0
this.step = this.step % 36; //(thanks Neikos!)
}
}
ShapePoint.prototype = new Point();
So I've spent hours tweaking different things, and I cannot for the life of me see what the problem is! If anybody can figure it out, it would be fantastic. If you need more context as to how exactly this is implemented, I've created a JSFiddle for you. Thanks in advance, this place is always so helpfull!
EDIT :: I do realize my code is a bit clunky, but I typing out what everything does really helps me learn for the next time
user2310289 is correct in his/her comment above: you're using a single global i variable in both stepPoints and tick, so these methods are interfering with each other.
There are some languages where a variable used in a method is implicitly local unless declared otherwise, but JavaScript is not one of those languages. In JavaScript you need to use the var keyword to declare your local variables, otherwise they are implicitly global.

Categories

Resources