Make ball move away from ball on click - javascript

There are some questions similar to this one and I have read them all but what I need is of a very specific nature.
Essentially I have a ball with a round area around it that can be clicked.
When you click this area, the ball should move in the direction opposite to the direction of the click compared to the center of the ball. So if you click right under the ball it should move up.
I have managed to this this by using the following
function clickBall(event){
//finding position of click
var rect = document.getElementById("theBall").getBoundingClientRect();
var ballX=rect.left-294.8641870117188;
var ballY=rect.top-60.125;
click[0] = event.clientX-313.999593505859423; click[1] = event.clientY-79;
distanceX=ballX-click[0]; console.log(distanceX);
distanceY=ballY-click[1]; console.log(distanceY);
ballMoving=true;
ballPosition = click;
//document.getElementById("theBall").style.left=(ballX+distanceX)+"px";
//document.getElementById("theBall").style.top=(ballY+distanceY)+"px";
}
moveBall gets called by update which runs every frame
function moveBall(){
if(ballMoving){
moveTime-=1;
if(moveTime<0){ //control move time
moveTime=ballMoveTime;
ballMoving=false;
}
ballPosition[0]+=distanceX/150*moveTime;
ballPosition[1]+=distanceY/150*moveTime;
ballSpeed-=ballSpeedReducion;
checkCollision();
document.getElementById("theBall").style.left=ballPosition[0]+"px";
document.getElementById("theBall").style.top=ballPosition[1]+"px";
}
}
sorry about all the weird numbers i had to do some adjustments, but anyways.
The problem with this is, it makes the ball move away from the click point, but if you click really close to the ball, it moves just a little, and if u click as far away as u can inside the blue area, it moves way too much.
I tried to solve this by having if statements that find if X and Y are positive or negative and makes them 1 or -1 accordingly, but this makes them only be able to move diagonally...
I need a way to make it so it moves just as much no matter how far the click is from the ball. Any suggestions would be appreciated.

Related

how can i increase mouse pointer area in javascript?

I make the game "bugs killer" with mouse pointer, and I use the bottle image on a cursor that spray on bugs,
but the problem is that spray not kill the bugs, when bottle goes on bugs that kill with onclick.
so can any one tell me how can i solve this problem?
how can I increase mouse pointer area in javascript ????
This is the code of spray animation:
<script type="text/javascript">
// for Spray Animation
function clickEffect(e){
var d=document.createElement("div");
d.className="clickEffect";
d.style.top=e.clientY+"px";d.style.left=e.clientX+"px";
document.body.appendChild(d);
d.addEventListener('animationend',function(){d.parentElement.removeChild(a);}.bind(this));}
document.addEventListener('click',clickEffect);
</script>
You can't "increase" the mouse pointer.
What you need to do is implement basic collision detection.
We can't tell you how to do it because there are whole books about this, but here are the steps i'd go through if i wanted a super-simple collision detection.
1) Register a click event and store the mouse position
2) Extend the mouse coordinates to cover a larger surface (for example leftLimit = mouseposition x - 10)
3) Loop through all your bugs or whatever you need to be able to click on. Calculate the space and position they occupy on your screen. If the bug's limit are within the range of the mouse click, destroy it

Canvas Ball bounces in wrong direction when pong paddle is moving

I would like to start off with a note. I tried using a jsfiddle but for some reason HTML5 canvas does not work. So as a workaround I used http://jsbin.com/gugihuwegopa/1/. To edit with this site, click the edit button at the top right corner of the window. Anyway, my problem is, when the paddle is not moving, the ball bounces correctly off all sides (The nomove variable has nothing to do with that, its just to make it disappear with the "w" key). However, when I move the paddle with the mouse towards the ball, it gets stuck inside the paddle. I think this is because it is not updating the location of the paddle fast enough so that the ball ends up inside of it, and my code continues to cause the ball to bounce even while inside. (until moving the paddle rapidly away and it gets unstuck). Yes I have tried putting the cxt.fillRect before the cxt.arc(). Sometimes the ball will travel through the paddle as well. I figure a way to fix this would be factoring in the direction of the ball in my two if statements:
if(y+ymove>=w && y+ymove<=w+h && x>=s && x<=s+l ) ymove*=-1; //top and bottom
if(x+xmove>=s && x+xmove<=s+l && y+ymove<=w+h && y+ymove>=w ) xmove*=-1; //left and right
Some other methods I have tried include:
if(y+ymove>=w && y+ymove<=w+h && x>=s && x<=s+l && centerY+17.5 < y+ymove+5 && centerX+12.5 < x+xmove+5) ymove*=-1; //top and bottom, extra +5 for radius
if(x+xmove>=s && x+xmove<=s+l && y+ymove<=w+h && y+ymove>=w && centerX+12.5 < x+xmove+5 && centerY+17.5 < y+ymove+5) xmove*=-1; //left and right
So basically I just need the ball to bounce correctly no matter how I move the paddle. Feel free to edit all you want, even if it means adding more if statements. All I ask is absolutely NO JQuery. Thanks in advance.
I would recommend to do your code more friendly in order to get help, removing comments and keep only the parts you need to fix.
About your problem one thing you could do is to use a flag, if the ball is hitting the paddle set the flag to True, do the redirection once and stop checking for the collision until the flag is false.
For sure there should be a better workaround but that's a start.
You must think of collision handling as having (at least) two phases : Collision detection and Collision resolution. Here you solve the collision only by changing speed, but both objects might still intersect if one speed is very high : one object might well be inside the other : So you have also to solve position, or, if you prefer 'push' the ligthest object out of the heaviest. You can do this by using a few min/max on the x,y,w,h of both objects.
OR, There's another 'dynamic' method to avoid object overlap : Have the collision handling time-driven. Split the collision handling into time sub-steps, making a stop on each collision. You must compute the time when the next collision will happen, then move everyone to that time, then update only the speeds, and do this again until enough time elapsed. So there not even a chance an overlap can happen : you 'stop the watch' on collision, then change speed, then restart time again. And several collision can happen in one frame, a case that won't be handled properly by a single-pass algorithm (case when a ball hit near a corner).
An example : Say your game frame time, 'dt' is 16 ms, now you detect the ball hits paddle at 10.2ms -> you make both object moves for 10.2ms (x+=vx*10.2/y...), solve their speed (only), then you ask your collision engine to iterate a further 5.8ms.
It's a little work but i did it in my game engine, it works fine.
(Hope i've been more helping than confusing... :-) )

How to rotate div in circular motion while counter rotating inner circles?

This image is what I am trying to achieve. Circles on the edges are clickable. Its structure is made such that each rotation will be multiple of 45 deg.
I am using css transform rotate property for rotation.
How is it supposed to work?
When we click on any circle on the edge it should come to its active position and it should always rotate in clockwise direction.
Here is what I did
I achieved rotation by assigning numbers to the circles.
i.e., if clicked on 7 number then it will rotate by angle (9-7)*45=90 degrees.
(This time I did not change the numbers dynamically. i.e., as the circle is rotating the numbers given to the circles are the same.)
This works fine here. But, lets see this scenario: when we click on 2nd position circle it will rotate by 315 deg and then if you click again on the same (second) position then it will make the angle of 270 and it rotates the div in anti-clockwise direction. I think this is its behavior. But, I don't want this to happen. It should rotate again in clockwise direction and should take the active position.
Now to achieve above I did this:
Adding angle with prev angle.
var prev_degree = prev_degree + current_degree;
(current degree is being calculated using the same formula from above.)
This time I changed numbers dynamically i.e., on each click numbers are given to the desired positions. Starting 1 as from Active position till 8 as shown in Image
But this time, when I rotate circle 1, 2 times it rotates perfect then it starts working strange. If you are constantly clicking on the same number then it will add the same angle and will keep rotating perfect no matter what your angle is. If you click on random circles then it wont work which is totally wrong.
Why clockwise?
Because the circles on edges, they contain icon of which I have to maintain position when whole circle rotates.(I can achieve that rotating circles on the edges by assigning negative angles. But, now this is not a problem.)
There is no case when I am getting negative angle.
Let me know if you are not clear with my question.
Please let me know your suggestions to make this work :-)

Understanding rotation and calculating the top left point in KineticJS

I am working on a page where I can view images. I want to create a rotation tool. I've done that, but, it's not working consistently. When I set up the centre point to rotate by, the image jumps slightly, and it gets worse each time. I was experimenting, and, I have code to add a wedge to the top left corner of my top level group ( so, at 0,0 ). If I rotate the image by 45 degrees and drag it so that half of it is off the left edge of my canvas, then I call getAbsolutePosition on the wedge and on the group, I get these values:
layer.getAbsolutePosition()
Object {x: 104.66479545850302, y: 279.2748571151325}
wedge.getAbsolutePosition()
Object {x: 180.2684127179338, y: -73.48773356791764}
I think this means my y position is actually the bottom of the image, which is off screen.
What I want to do, is calculate the absolute position of the middle of my image, when the mouse moves over it, regardless of it's rotation. I have some code that works out points with rotation, which seems like it works at first, almost, but it just gets more and more broken the more I use the tool. I feel like there's something about how Kinetic is tracking these things and what it's reporting, that I am missing. Any hints would be most appreciated. Tutorials I can read are even better ( yes, I've read everything linked from the KineticJS site and searched the web ).
In a nutshell, the question is, if I have an image inside a group, and it's rotated, how do I work out the centre point of the image, taking the rotation in to account, and how do I set the offset so it will rotate from that point, and stay in the same place ?
Thanks
As you've discovered about KinetiJS:
rotation is easy
dragging is easy
dragging+rotation is difficult
After you drag your image you must reset its rotation point (offsetX/offsetY).
KineticJS makes dragging+rotation more difficult than it has to be.
Resetting the offset points of your image will cause KineticJS to automatically move your image (Noooo!!).
That's what's causing your jumping.
The solution to the "jumping" problem:
When you reset the image's rotation point (offsetX/OffsetY) you must also reset the image's X/Y position.
This code resets both XY and Offsets for an image after dragging:
A Demo: http://jsfiddle.net/m1erickson/m9Nw7/
// calc new position and offset
var pos=rect.getPosition();
var size=rect.getSize();
var offset=rect.getOffset();
var newX=pos.x-offset.x+size.width/2;
var newY=pos.y-offset.y+size.height/2;
// reset both position and offset
rect.setPosition([newX,newY]);
rect.setOffset(size.width/2,size.height/2);

What is a good technique for detecting mouse movement distance in Javascript?

I'm designing user controls and I'm trying to code the controls for the mouse. This is what I came up with to get user input.
var mouseInput = new GLGE.MouseInput(window);
window.onmousemove = function(ev){
var dx = window.mouseX - prevMousePos.x;
var dy = window.mouseY - prevMousePos.y;
prevMousePos ={
x:window.mouseX,
y:window.mouseY
};
// I do movement calculations with dx and dy here
}
However what I came up with above isn't perfect because if the mouse reaches the end of the window it would not detect movement.
Is there a better way of detecting mouse movement? I'd rather not calculate it using its co-ordinates because using that method I'm unable to calculate distance moved when the mouse is at the edge of the screen.
PS: If anyone was wondering, what I'm designing is sorta like Google Streetview or a first person shooter. I just want the user to be able to move the mouse in one direction infinitely.
I mean, you're already using an onmuseover event handler (the most efficient way because Javascript is async). So you just compute distances from he previous, only when the user moves the mouse. If he doesn't further move the muse, the player just proceeds in the same direction prviously computed.
No, there is no method to handle mouse movements outside of the browser window.

Categories