I want to make a constructor function that creates circle objects. I need to add two methods to it. I want first method (translate()) to takes two number parameters and adds the first one to the Circle's x-coordinate and adds the second one to the Circle's y-coordinate.
and I want the second method to take a Circle parameter and return yes if the two Circles intersect, but return false otherwise.
function Circle (xPoint, yPoint, radius) {
this.x = xPoint;
this.y = yPoint;
this.r = radius;
}
function translate(horiz, vert) {
return ((horiz + this.x) && (vert + this.y));
}
How would I implement the second, intersects(), method?
Here you go:
function Circle(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.translate = function(h, v) {
this.x += h;
this.y += v;
};
this.intersect = function(circle) {
var centerDistance = Math.pow(this.x - circle.x, 2) + Math.pow(this.y - circle.y, 2);
return Math.pow(this.r - circle.r, 2) <= centerDistance && centerDistance <= Math.pow(this.r + cirle.r, 2);
};
}
Related
I have this class:
class AGV {
constructor(id, x, y, agvcolor, matrixTable) {
this.id = id;
this.x = x;
this.y = y;
this.color = agvcolor;
this.xOffset = 1;
this.yOffset = 1;
this.matrix = matrixTable;
}
setX(newX) {
this.x = newX;
}
setY(newY) {
this.y = newY;
}
lastCoordinates() {
return JSON.stringify({
'x': this.x,
'y': this.y
});
}
spawn() {
var xCoord = this.x - this.xOffset;
var yCoord = this.y - this.yOffset;
var cell = this.matrix.childNodes[1].children[yCoord].children[xCoord];
cell.style.background = this.color;
cell.innerHTML = this.id;
}
moveToCell(x, y) {
console.log("rolling to x: " + x + " y: " + y);
this.clearPreviousCell(this.x, this.y);
// offsets are needed to convert array index to actual position
var xCoord = x - xOffset;
var yCoord = y - yOffset;
var cell = this.matrix.childNodes[1].children[yCoord].children[xCoord];
cell.style.background = this.color;
cell.innerHTML = this.id;
}
clearPreviousCell(x, y) {
var xCoord = x - xOffset;
var yCoord = y - yOffset;
var cell = this.matrix.childNodes[1].children[yCoord].children[xCoord];
cell.style.background = "#fff";
cell.innerHTML = "";
}
runTask(x, y, z) {
console.log("Running task. Target: X: " + x + " Y: " + y);
if (this.x < x) {
//while (this.x < x) {
this.x += 1;
setTimeout(function() {
moveToCell(this.x, y);
}, 800);
//}
}
}
}
And whenever I call moveToCell() function inside function runTask(), I get an error stating that the "moveToCell" function is not defined and as so, I cannot update the object's position in the map.
I've also tried this.moveToCell() insted, but results in the same problem. I don't understand what is wrong here.
Can anyone please post any thoughts on this? Thanks in advance
You need to specify the instance to call the method on, which should be this.
Also, this is not saved in normal closures. Use an arrow function to keep the context.
runTask(x, y, z) {
console.log("Running task. Target: X: " + x + " Y: " + y);
if (this.x < x) {
//while (this.x < x) {
this.x += 1;
setTimeout(() => this.moveToCell(this.x, y), 800);
//}
}
}
Since it's inside the class, you need to use the this operator. Change it to:
this.moveToCell(this.x, y);
As you're using it within setTimeout(function () { ... }), you need to cache this:
this.x += 1;
_this = this;
setTimeout(function() {
_this.moveToCell(this.x, y);
}, 800);
I am trying to call a function does multiplication On another function that accepts two numbers as parameters. i Have tried using constructor and nested function, but to no avail. i have tried the followings:
function Coordinate(a, b) {
var x, y;
return {x: a, y: b};
function multiply(n) {
x * n;
y * n;
}
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiple(2));
// expected output: 4 6;
You should set multiply to be on the Coordinate's prototype so that when you call new Coordinate, the instantiated object will have multiply as a method. For it to work, you should also set this.x and this.y instead of returning an object directly:
function Coordinate(a, b) {
this.x = a;
this.y = b;
}
Coordinate.prototype.multiply = function(n) {
this.x *= n;
this.y *= n;
return this;
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiply(2));
Or, if you wanted multiply to return just the multiplied coordinates without changing the original object, then return the coordinates alone:
function Coordinate(a, b) {
this.x = a;
this.y = b;
}
Coordinate.prototype.multiply = function(n) {
return [this.x * n, this.y * n];
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiply(2));
The answer modified two parts:
the creation of Coordinate members
multiple -> multiply
Hope this help :)
function Coordinate(a, b) {
this.x = a;
this.y = b;
this.multiply = function(n) {
return this.x * n + " " + this.y * n;
}
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiply(2));
Well, firstly your console.log is calling multiple, not multiply.
Second, try an approach like this:
function Coordinate( a, b )
{
function multiply( n )
{
this.x = this.x * n;
this.y = this.y * n;
return this;
}
var co = { x: a, y : b };
co.multiply = multiply.bind( co );
return co;
}
Having clarified in the comments, the (simplest)solution is:
// important code
function Coordinate(a,b) {
this.x = a;
this.y = b;
this.multiply = function (n) {
this.x = this.x*n;
this.y = this.y*n;
}
}
// test code
let coord = new Coordinate(2,3);
console.log("Original Coordinate:");
console.log(coord);
coord.multiply(2);
console.log("Changed Coordinate: ");
console.log(coord);
You could also put the function in the prototype if you don't want a copy of it in every Coordinate object.
I have a card class:
function Card() {
this.image = new Image();
this.x = 0;
this.y = 400;
this.initialX = 0;
this.initialY = 0;
this.scaleFactor = 4;
this.setImage = function(ii){
this.image.src = ii;
};
this.getWidth = function(){
if (this.image == null){
return 0;
}
return this.image.width / this.scaleFactor;
}
this.getHeight = function(){
if (this.image == null){
return 0;
}
return this.image.height / this.scaleFactor;
}
this.pointIsInCard = function(mx, my){
if (mx >= this.x && mx <= (this.x + this.getWidth()) && my >= this.y && my <= (this.y + this.getHeight()))
{
return true;
}
else{
return false;
}
};
};
I then have a deck class:
function Deck(x, y, w, h){
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.cards = [];
}
I need to add a method in Deck class similar to pointIsInCard instead it will be called pointIsInDeck. The logic will be same i.e to check whether the passed in point falls in the boundary of the object. So seeing this duplication of code I wanted to know what is a good design practice to avoid this duplication? One option I thought of was to extract the method out and create a function for generic object with x, y, width, height but again from OOP principles I thought this method should belong to the class/object. I appreciate any help! Thanks!
A common approach for what you're doing is to attach a Rectangle or similar instance with that functionality to both of your objects, that is:
class Rectangle {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
containsPoint(x, y) {
return x >= this.x && x =< this.width &&
y >= this.y && y =< this.height;
}
}
Then just add it to Card and Deck:
function Card() {
this.rect = new Rectangle(/* Your card shape */);
// ...
}
function Deck() {
this.rect = new Rectangle(/* Your deck shape */);
// ...
}
And you can do:
card.rect.containsPoint();
deck.rect.containsPoint();
If these are classes related to drawing, they would both inherit from something like Rectangle, which they would both inherit this behaviour from.
If they are gameplay-related, I would prefer them each referencing a Rectangle (or its subclass) that they would delegate all UI-related tasks to; then reduce this to the previous paragraph's solution.
You can use Function.prototype.call() to set this at a function call
function Card() {
this.x = 1; this.y = 2;
};
function Deck() {
this.x = 10; this.y = 20;
}
function points(x, y) {
// do stuff
console.log(x, this.x, y, this.y); // `this`: `c` or `d`
}
var c = new Card();
var d = new Deck();
points.call(c, 3, 4); // `this`: `c` within `points` call
points.call(d, 100, 200); // `this`: `d` within `points` call
I have written a code with constructer Vector(it has two parameters) and I wish to pass different set of parameters through a prototype function and want to sum up the values for both set of parameters.
But I am facing a issue with printing final Vector.
function Vector(x, y) {
this.x = x;
this.y = y;
console.log(x, y);//initially this prints (3,3)
return (x, y);
}
Vector.prototype.plus = function (a, b) {
this.x = this.x + a;
this.y = this.y + b;
console.log(this.x, this.y);// After passing (1,9) it prints (4,12)but
return (this.x, this.y); //after returning (this.x, this.y) it
//prints only Y coordinate as 12
}
var type_vector = new Vector(3, 3);
console.log(type_vector.plus(1, 9));
Output: (3,3),(4,12),12
I believe you're from a python background, for there (x, y) is returned as a tuple. In JS if you return (x, y); it will be the value at the closing parenthesis (y, in this case). You must use an object or an array for your objective.
try this on console:
var a = (3, 4, 5, 6);
console.log(a);
Well, in JavaScript if you want to return an array you can use the [] notation.
Diff. this with you version :
function Vector(x, y) {
this.x = x;
this.y = y;
console.log(x, y);
return this;
}
Vector.prototype.plus = function(a, b) {
this.x = this.x + a;
this.y = this.y + b;
console.log(this.x, this.y);
return [this.x, this.y];
};
var type_vector = new Vector(3, 3);
console.log(type_vector.plus(1, 9));
How do i get the point of intersection of a line and a circle.. I got lots of information on this topic, but my requirement is not matching..
I got a line whose one end point lies at the origin of the circle.. and other end lies somewhere outside the circle.. Now i need the point of intersection of this line and circle..
I have tried to find closest edge point from outside the circle using below formula however unable to crack it -
closestCirclePoint = function(px, py, x, y, ray){
var tg = (x += ray, y += ray, 0);
return function(x, y, x0, y0){return Math.sqrt((x -= x0) * x + (y -= y0) * y);}(px, py, x, y) > ray ?
{x: Math.cos(tg = Math.atan2(py - y, px - x)) * ray + x, y: Math.sin(tg) * ray + y}
//{x: (px - x) / (length / ray) + x, y: (py - y) / (length / ray) + y}
: {x: px, y: py};
};
Any way to get the solution for this problem..??
Thanks in advance!
A JavaScript Version of Lindenhovius answer would look like this:
/**
* Finds the intersection between a circles border
* and a line from the origin to the otherLineEndPoint.
* #param {Vector} origin - center of the circle and start of the line
* #param {number} radius - radius of the circle
* #param {Vector} otherLineEndPoint - end of the line
* #return {Vector} - point of the intersection
*/
function findIntersect (origin, radius, otherLineEndPoint) {
var v = otherLineEndPoint.subtract(origin);
var lineLength = v.length();
if (lineLength === 0) throw new Error("Length has to be positive");
v = v.normalize();
return origin.add(v.multiplyScalar(radius));
}
But you need to implement the vector "class"* your self:
function Vector (x, y) {
this.x = x || 0;
this.y = y || 0;
}
Vector.prototype.add = function (vector) {
return new Vector(this.x + vector.x, this.y + vector.y);
};
Vector.prototype.subtract = function (vector) {
return new Vector(this.x - vector.x, this.y - vector.y);
};
Vector.prototype.multiply = function (vector) {
return new Vector(this.x * vector.x, this.y * vector.y);
};
Vector.prototype.multiplyScalar = function (scalar) {
return new Vector(this.x * scalar, this.y * scalar);
};
Vector.prototype.divide = function (vector) {
return new Vector(this.x / vector.x, this.y / vector.y);
};
Vector.prototype.divideScalar = function (scalar) {
return new Vector(this.x / scalar, this.y / scalar);
};
Vector.prototype.length = function () {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
};
Vector.prototype.normalize = function () {
return this.divideScalar(this.length());
};
*there are no real classes in JavaScript — just constructor functions and prototypes, things change with ES6 but that's another topic.
Simple solution in pesudocode:
Point findIntersect (Point origin, double radius, Point otherLineEndPoint) {
Vector v = otherLineEndPoint - origin;
double lineLength = v.length();
assert (!Math.isZero(lineLength)); //assert line has positive length
v = v / lineLength; //normalize v
return origin + v * radius;
}
As a typescript class, don't know how to operator overload however:
class Vector {
constructor(public x = 0, public y = 0) {}
add = (vector: Vector) => new Vector(this.x + vector.x, this.y + vector.y)
subtract = (vector: Vector) => new Vector(this.x - vector.x, this.y - vector.y)
multiply = (vector: Vector) => new Vector(this.x * vector.x, this.y * vector.y)
multiplyScalar = (scalar: number) => new Vector(this.x * scalar, this.y * scalar)
divide = (vector: Vector) => new Vector(this.x / vector.x, this.y / vector.y)
divideScalar = (scalar: number): Vector => new Vector(this.x / scalar, this.y / scalar)
length = (): number => Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2))
normalize = () => this.divideScalar(this.length())
findIntersect(o: Vector, p: Vector, radius: number) {
let v = p.subtract(o)
const lineLength = v.length()
if (lineLength === 0) throw new Error('Length must be positive')
v = v.normalize()
return o.add(v.multiplyScalar(radius))
}
}