How to check if an object is hitting another object during animation. - javascript

Hello and thanks for your time and help. I am building a mini golf game using HTML 5 Canvas. I have a golf ball that is able to be hit around with a specific power and direction and stoping and slowing down accordingly.
However, i am stuck on finding a optimal way of detecting wether the ball is hitting or over an obstacle on the course. I have each of the obstacle objects stored in an array. So it is easy to access the x,y,height, and width of the object. I was thinking it would be best to have a for loop that goes through each of the objects checking if the ball is hitting any of them during animation. Also the x and y of the golf ball is easily accessible, its values are stored in a dictionary.
Any suggestions of testing to see if any of the obstacles are being hit?
Here is the code on how i am testing for the boundaries and having the ball bounce back correctly
function animateGolfBall(timestamp){
if(powerBar.widthChange != 0){
context.clearRect(0, 0, canvasTag.width, canvasTag.height);
if (golfBall.x > canvasTag.width - 5 || golfBall.x < 5 ) {
golfBall.angle = 180 - golfBall.angle;
updateGolfBall();
drawEverything();
}
else if (golfBall.y > canvasTag.height - 5 || golfBall.y < 5) {
golfBall.angle = 360 - golfBall.angle;
updateGolfBall();
drawEverything();
}
else{
updateGolfBall();
drawEverything();
}
window.requestAnimationFrame(animateGolfBall);
powerBar.widthChange -= 1;
}
else{
golfBall.isMoving = false;
drawEverything();
}
}
Here is the code where the obstacles are being redrawn, and where i believe the check should be placed to see if the golf ball is hitting them
function drawObstacle(){
for(var i = 0; i < obsticles.length; i++){
obsticles[i].createSquare(obsticles[i].squareX/canvasTag.width,
obsticles[i].squareY/canvasTag.height,
obsticles[i].squareWidth/canvasTag.width,
0,
obsticles[i].squareHeight/canvasTag.height,
0,"pink",3,"yellow");
// if { need help with logic here
//And what to put here, and how ever many logical statements will be needed
// }
}
Any help or tips would be much appreciated. If you need more code or i wasn't clear on something please let me know and ill update my question.

This is called collision detection. There are many ways to deal with collisions. Depending on the shape of your objects (are they circles or squares or car-shaped) and what you want to happen when a collision occurs. Does the ball bounce back? Does it stop? Is it of the most importance that the collision is detected at the edge of the object?
You can read about simple collision detection working with either square or circle shaped objects here.

Related

in my JS game, the ball not going smooth angled. always making curve move. how can i fix it?

I'm making html+js game. In my game ball comes from on right with that code
for(let i = 0; i < this.loop.length; i++){
let ballNow = this.loop[i];
ballNow.x -= ballNow.speed;
and if character.x == ball.x, ball goes through. this is not problem.
but I try to give an angle to ball. like that
const dif = ball.loop[i].x - footballer.x - footballer.width/2;
ballNow.x += dif;
ball making curve. because every frame reference the ballNow.x and refresh himself i guess. For example when I wrote ballNow.x += 2, the ball going like what I want.
I tried 2 solutions. I think about this is reference problem and I tried object.assign and object.create methods. But always "dif" increased and ball made curve.
Ball going like this and what i want
What should I write for the ball going angled without curve move?
Note: I shouldn't use any library.

How to make multiple circle objects not go into each other with collision detection?

I have a total of 1 to 64 blobs and they all move to my mouse position. But i want them to not go into each other, in other words circle collision detection. However i can't seem to make it smooth and also push new objects after they move for the first time?
Tried checking each blob for collision with other blobs. If collosion is true, then set the distance between the blobs to their accumulated radiuses.
This is how i wrote the colliding function, but this way of doing it makes the resetting of positions too fast. I want it to be a smooth, but fast transition. Like instead of now 1 frame, lets say 10 frames. And another problem is when two objects' are distanced to their radiuses, they might collide into new ones and that will cause this code to run again, and then all blobs go crazy.
this.collide = function() {
var length = this.blobs.length; // How many blobs?
this.blobs.forEach(function(item, index) {
for (var i = 0; i < length; i++) {
// Get absolute distance between two vectors
var v0 = vectorFromTo(blob.blobs[i].pos.x, blob.blobs[i].pos.y, //[x2, y2]
item.pos.x, item.pos.y); //[x1, y1]
// if colliding, set distance between to their accumulated radiuses
if (magnitude(v0) < blob.blobs[i].r + item.r) {
item.pos.add(v0.setMag(magnitude(v0) - (blob.blobs[i].r + item.r)));
}
}
});
}
I haven't tried to code another way of doing this yet because i haven't learned about vectors in school, but i do understand them quite a bit. But what i think would work is if i checked for collision, and if they collide they go opposite directions 50% of the deficit distance, and then they check if they hit new blobs. But this would require physics right? Cause then it would have to do something with the mass and speed of the blob as well to know whats gonna happen to the new blob it crashes into?
EDIT:
This is what im looking for: https://youtu.be/QvlhRGtlcsw
This is what it currently looks like: https://youtu.be/QEpHnCgomqY

Creating a collision effect three.js

So for a game that I am making (my first game) I have made an endless scroller and everything is working perfect. The only issue I am have is with creating a collision like effect. For the time being the only thing I want to happen when the objects collide is to post to the console saying 'collision'. This is the collision function that I have made :
function collision () {
distance = Math.sqrt(
((engine.x - obstacles[i].x) * (engine.x – obstacles[i].x))
+ ((engine.y - obstacles[i].y) * (engine.y – obstacles[i].y))
);
if (distance < engine.radius + obstacles[i].radius)
{
console.log("collision");
//objects should collide
}
}
Engine in this case being a cube and the obstacles[i] array is an series of cylinders coming toward the cube.
and I have called the function within my ini function(). But for some reason I am not getting anything posted to the console.
I may be way off here, but if anyone has any suggestions that would be great.

Raycasting to make an enemy jump

As stated above, I am trying to build a simple game, but I can't seem to get the enemies moving correctly. The game is a Minecraft style block-based game. The code I am using so far makes the enemy start following me when I get within a certain distance and stop following once I get a certain distance away.
The problem I am having with this script is that the enemy sort of floats off into the distance when I escape him. More importantly, I cannot for the life of me get the enemy to jump. I know that I should be using two Raycasts for this: one to detect a block in front which will make the enemy jump and another to detect below the enemy and let him fall to the level below if there is no collier at his feet? I have no idea how to go about implementing this and some help would be greatly appreciated.
The code I have thus far can be seen below:
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var range : float=10f;
var range2 : float=10f;
var stop : float=0;
var myTransform : Transform; //current transform data of this enemy
function Awake() {
myTransform = transform; //cache transform data for easy access/preformance
}
function Start() {
target = GameObject.FindWithTag("1Player").transform; //target the player
}
function Update () {
//rotate to look at the player
var distance = Vector3.Distance(myTransform.position, target.position);
if (distance<=range2 && distance>=range) {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position),
rotationSpeed*Time.deltaTime);
} else if (distance <= range && distance > stop) {
//move towards the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position),
rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
} else if (distance <= stop) {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position),
rotationSpeed*Time.deltaTime);
}
//lock rotation on x and y axis to zero
myTransform.eulerAngles = new Vector3(0f, myTransform.eulerAngles.y, 0);
}
The design can change really a lot. It depends how clever AI do you want ? And how realistic it should be. Firstly you should check distance and as I saw you did that. The question is what if there is a wall or something ? Maybe they are so close to each other but there is a wall between them. This is why you need raycast. So you send a raycast from enemy to player. If there is no obstacle between them AI can decide that "aye I should come after you". But here is another problem for being realistic. What if its not looking to you ? If the AI can spot the player when it looks somewhere else, it is not that cool right ? So you also check if the player is in front of the AI. Maybe we can do it like this :
var heading = target.position - transform.position;
var dot: float = Vector3.Dot(heading, transform.forward);
so if dot is -1 we can say it is directly behind and +1 means in front of it. Well, now another problem. If player should be in front of the AI to be spotted then AI can not stand right ? It should move and turn around randomly. We can work on that later if you gonan need it.
Now another problem what if you hide after an object ? What it should do ? I mean when you are running if something came between you and AI, since raycast will fail it will stop following you right ? What we can do for it ? My sugesstion store the last position of the player which AI saw. And at least go to there to check if AI can find the player there. If it cant, it may keep moving randomly. By doing this it will looks more realistic I believe.
Edit: Lol I realised that i just improved you design and forgot to answer what exactly you asked.
Firstly AI shoudl know if it is grounded or not. What we need to know first distance to ground when we send raycast we gonan need it.
var distanceToGround = GetComponent<Collider>().bounds.extents.y;
function boolean isGrounded(){
return Physics.Raycast(transform.position, -Vector3.up, distanceToGround + 0, 1);
}
AI should send a raycast not from its head more like below the knees. Not send it too far away just a little distance will be enough. It is just to understand it there is an obstacle. And also send another raycast but this time now below the knees. From the jump height. And if it dont hit anything we can decide that there is an obstacle (first raycast says that) but AI can jump over it (second raycast says that). After deciding it, if AI also grounded that means it can jump and pass trough the obstacle.
Lets say this is the part 1. If you want me to keep telling, I can write another part for you. Have a nice day !

Check if two objects are facing eachother

I've searched all over and couldn't find an answer to this seemingly common question, surprisingly. The problem I'm currently facing is checking if the player is facing an enemy, then if so within what range of the players' view (adjustable) and if it's within that range then move away in the nearest safe direction.
Here's a picture :D
So, how would I accomplish this? I have the x, y, and direction, of every ship object. This is my last failed attempt, attempting to consider that the player's direction will be exactly 180 degrees away from the enemy's direction relative to the player.
var direction=Math.direction(this.x,this.y,player.x,player.y,1),
playerview=Math.abs(direction)-Math.abs(player.direction-180)
if(Math.abs(playerview)<10) {
console.log('in view')
this.xVelocity+=AI.speed*Math.sin(playerview*Math.PI/180)
this.xVelocity+=AI.speed*Math.cos(playerview*Math.PI/180)
}
In this example, 10 would be the range. Of course, I've only managed to make ships rotate to the right, so aside from the detection only working on half a circle I can't make the enemy go to the right side either. Any ideas?
In Your code, You are modifying this.xVelocity twice instead of modifying this.yVelocity.
I guess, Math.direction is not in the JavaScript/ECMA standard. Are You sure, You are using it correctly? Consider Math.atan2.
Moreover, You should provide a definition of "facing each other".
If it's "seeing each other", then Your comment "in view" is misleading.
But the main issue is:
Math.abs(angleInDegrees) modifies the angle!
The correct way to build an absolute value of an angle is:
while (angleInDegrees < 0)
{
angleInDegrees += 360;
}
// If necessary, add this too:
while (angleInDegrees >= 360)
{
angleInDegrees -= 360;
}
-10 and 350 are identical, -10 and 10 are 20 degrees apart.
For further explanation, let's call the code above normalizeAngle
(Note: For huge values, the loop may run very long or even forever. If such values may occur, this should be checked.)
The following should do the trick:
playerview = normalizeAngle(direction - player.direction - 180)
if (playerview < range || playerview > 360-range) {
By the way: "playerview" should be the mininum from the player's field of view and the enemy's field of view.

Categories

Resources