Touchend will cancel on canvas and doesnt fires - javascript

I have a weird problem. I'm creating a test game.Which uses touch events and canvas.There is a ball that you can push it and when you release your finger it must go(something like angry birds).
I made that in mouse and it work correctly.I wanna make it on android. But it doesn't run.But when you use 2 finger it works correctly.
I'm sure the problem is here :
canvas.addEventListener("touchstart",function(event){
event.preventDefault();
if (event.touches[0].clientX >= x && event.touches[0].clientX <= x + (radius * 2) && event.touches[0].clientY >= y && event.touches[0].clientY <= y + (radius * 2)) {
dx = 0;
dy = 0;
isindrag = true;
oldx = x;
oldy = y;
}
});
canvas.addEventListener("touchmove", function (event) {
event.preventDefault();
if (isindrag) {
x = event.touches[0].clientX;
y = event.touches[0].clientY;
}
});
canvas.addEventListener("touchend", function (event) {
var touchX = event.touches[0].clientX;
var touchY = event.touches[0].clientY;
if (isindrag && touchX < canvas.width && touchY < canvas.height && touchX > 0 && touchY > 0) {
isindrag = false;
dx = -(x - oldx) / 30;
dy = -(y - oldy) / 30;
ismoving = true;
}
});
canvas.addEventListener("touchcancel", function(event){
event.preventDefault();
});
x : x of ball
y : y of ball
dx : Delta x of ball
dy : delta y of ball
radius : radius of ball
Can you help me?

The touches object of a touch event contains a collection of points currently on the screen. Now imagine that you put a single finger onto the surface and release it. This will trigger a touchend event but as the touches object just contains information on the active 'fingers', it will come up empty thus there is no clientX or clientY property to query. In a touchend event handler you need to use changedTouches instead of touches.
So try changing
var touchX = event.touches[0].clientX;
var touchY = event.touches[0].clientY;
to
var touchX = event.changedTouches[0].clientX;
var touchY = event.changedTouches[0].clientY;

Related

move div towards mouse at same speed per second

I have created the following code to make the player move towards the mouse, JSFiddle
Code
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(event) {
mouseX = event.pageX;
mouseY = event.pageY;
});
$(function(){
var $map = $(".map");
var $player = $('.player');
var centerPlayerX = $player.offset().left + $player.width() / 2;
var centerPlayerY = $player.offset().top + $player.height() / 2;
var movingInterval;
$('.map').on('mousedown', function(event){
movingInterval = setInterval(function(){
var clickedPosX = mouseX,
clickedPosY = mouseY;
var currentMapPositionX = parseFloat($map.css("background-position-x"));
var currentMapPositionY = parseFloat($map.css("background-position-y"));
var moveMapX = currentMapPositionX - clickedPosX/100 + centerPlayerX/100;
var moveMapY = currentMapPositionY - clickedPosY/100 + centerPlayerY/100;
$map.css({ "background-position-x": `${moveMapX}px`, "background-position-y": `${moveMapY}px` });
var angle = getDirection(centerPlayerX, clickedPosY, clickedPosX, centerPlayerY);
$player.find('.ship').css('transform', 'rotate('+angle+'deg)');
}, 10);
}).on('mouseup', function() {
clearInterval(movingInterval);
});;
});
function getDirection(x1, y1, x2, y2){
var dx = x2 - x1;
var dy = y2 - y1;
return Math.atan2(dx, dy) / Math.PI * 180;
}
Problem
var moveMapX = currentMapPositionX - clickedPosX/100 + centerPlayerX/100;
var moveMapY = currentMapPositionY - clickedPosY/100 + centerPlayerY/100;
Problem is that I want to move the player at a set speed (px*ps). Currently the player will increase in speed when the player moves his mouse further away from the image. I currently have no idea on how I would move the player at a set speed. Therefore I would need to remove clickedPosY/X somehow and change it to a static speed but the image should still move towards were the mouse is, which is the problem.
So, let's assume you have a speed constant; what you want to do is to project the speed constant along the movement vector. The easiest way to do that is to scale the components of the offset to the click position by the ratio of the speed to the distance between the click point and the movement base:
var distanceX = clickedPosX - centerPlayerX;
var distanceY = clickedPosY - centerPlayerY;
var magnitude = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
var deltaX = distanceX * speed / magnitude;
var deltaY = distanceY * speed / magnitude;
var moveMapX = currentMapPositionX - deltaX;
var moveMapY = currentMapPositionY - deltaY;
Updated fiddle

Javascript/Canvas: Mouse coordinates don't match after scaling (collision)

After resizing the square, there is a collision problem, GIF animation problem, sample https://jsfiddle.net/8jkxdhfv/. What can i do? Should i untransformed mouse coordinates to transformed coordinates ? But how? How can i update x and y in my collision function?
HTML
<canvas id="test" width="480" height="380"></canvas>
<div id="text">Use mouse wheel to change square size</div>
JAVASCRIPT
var ctx = test.getContext('2d');
var obj = { x:100,y: 100,width: 100,height: 100}
var mouse = {x:0, y:0, width:10, height:10};
var zoom = 1;
setInterval(function(){
ctx.clearRect(0,0,test.width,test.height);
ctx.save();
var cx = obj.x+obj.width/2;
var cy = obj.y+obj.height/2;
// draw
ctx.translate(cx, cy);
ctx.scale(zoom,zoom);
ctx.translate(-cx,-cy);
ctx.fillRect(obj.x,obj.y,obj.width,obj.height);
ctx.restore();
// check collision
if(collision(obj,mouse)){
ctx.fillText("===== COLLISION =====", 110,90);
}
},1000/60);
function collision(obj1,obj2){
if(obj1.x < obj2.x + obj2.width * zoom &&
(obj1.x + obj1.width * zoom) > obj2.x &&
obj1.y < obj2.y + obj2.height * zoom &&
(obj1.height * zoom + obj1.y) > obj2.y){
return true;
}
return false;
}
window.addEventListener('mousewheel', function(e){
if(e.deltaY>0 && zoom<2){
zoom+=0.5;
}
if(e.deltaY<0 && zoom>0.5){
zoom-=0.5;
}
}, false);
window.addEventListener('mousemove', function(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
}, false);
You are getting mouse position based on entire window, not canvas. Some math and you will get what you want.
test.addEventListener("mousemove", function(evt) {
var mousePos = getMousePos(test, evt);
mouse.x = mousePos.x;
mouse.y = mousePos.y;
});
function getMousePos(canvas, event) {
var rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
I have updated the function and it works:
function collision(obj1,obj2){
var eW = (obj1.width-(obj1.width*zoom))/2;
var eH = (obj1.height-(obj1.height*zoom))/2;
//console.log(eW);
if(obj1.x+eW < obj2.x + obj2.width * zoom &&
(obj1.x + obj1.width * zoom) + eW> obj2.x &&
obj1.y + eH < obj2.y + obj2.height * zoom &&
(obj1.height * zoom + obj1.y) + eH > obj2.y){
return true;
}
return false;
}

three.js rotate object on mouse down and move

I'm trying to get a good mouse movement in my scene so I can rotate around the object.
I have two problems, I can figure out how to limit the movement so that it never rotates below 0 degrees on the Y axis. (I dont want to see the object from below, only above)
And the second thing I can't figure out is how to make the movement smooth. Now with what I have achieved in the jsfiddle is that the camera moves back to its starting position before starting to rotate.
My try: http://jsfiddle.net/phacer/FHD8W/4/
This is the part I dont get:
var spdy = (HEIGHT_S / 2 - mouseY) / 100;
var spdx = (WIDTH / 2 - mouseX) / 100;
root.rotation.x += -(spdy/10);
root.rotation.y += -(spdx/10);
What I want without using an extra library: http://www.mrdoob.com/projects/voxels/#A/afeYl
You can rotate you scene with this code,
To ensure to not rotate under 0, simule rotation of a vector (0,0,1) and check if y of vector is negative
var mouseDown = false,
mouseX = 0,
mouseY = 0;
function onMouseMove(evt) {
if (!mouseDown) {
return;
}
evt.preventDefault();
var deltaX = evt.clientX - mouseX,
deltaY = evt.clientY - mouseY;
mouseX = evt.clientX;
mouseY = evt.clientY;
rotateScene(deltaX, deltaY);
}
function onMouseDown(evt) {
evt.preventDefault();
mouseDown = true;
mouseX = evt.clientX;
mouseY = evt.clientY;
}
function onMouseUp(evt) {
evt.preventDefault();
mouseDown = false;
}
function addMouseHandler(canvas) {
canvas.addEventListener('mousemove', function (e) {
onMouseMove(e);
}, false);
canvas.addEventListener('mousedown', function (e) {
onMouseDown(e);
}, false);
canvas.addEventListener('mouseup', function (e) {
onMouseUp(e);
}, false);
}
function rotateScene(deltaX, deltaY) {
root.rotation.y += deltaX / 100;
root.rotation.x += deltaY / 100;
}

Changing my Jquery project to plain javascript

I created a breakout game for a school project using jquery and a helpful online tutorial.
The working fiddle is here: http://jsfiddle.net/Kinetic915/kURvf/
EDIT revised fiddle: http://jsfiddle.net/Kinetic915/nVctR/
I have changed most to javascript but am having problems changing the jquery code that renders the ball to javascript.
I have Marked and left spaces in the areas where there are problems.
Thank you very much for any help given!!
//***********************************************************************************
// START CODE
//***********************************************************************************
// VARIABLES and other initializing functions are here
function start() {
//******************************************************************************
//JQUERY
// HERE IS THE MAIN PROBLEM!!!!!!
// HERE IS THE MAIN PROBLEM!!!!!!
Cir = $('#canvas')[0].getContext("2d");
//JQUERY
//changing to Cir = canvas.getContext("2d"); causes the code to FAIL.
return setInterval(drawCIRCLE, 10);
}
function windowsize() {
//success with javascript
WIDTH.width = window.innerWidth;
HEIGHT.height = window.innerHeight;
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
//Previous JQUERY:
// WIDTH = $("#canvas")[0].width = $(window).width();
// HEIGHT = $("#canvas")[0].height = $(window).height();
}
windowsize();
var x = WIDTH / 2 - 30; //divide by 2 start in middle of window
var y = HEIGHT / 2;
//THIS DRAWS THE CIRCLE
function circle() {
//Cir.clearRect(0, 0, WIDTH, HEIGHT);
Cir.beginPath();
Cir.arc(x, y, 10, 0, Math.PI * 2, true);
Cir.closePath();
Cir.fill();
}
// Initialization of the Block array, rendering of the gutter area and coordinate box
were here
//*********************************************************
// HERE IS THE CODE THAT RENDERS THE BALL MOVEMENT ETC.
//draw a circle
function drawCIRCLE() {
clear();
circle();
drawPADDLE(); //calls draw paddle function
drawGUTTER(); // calls draw gutter function
drawCOORBOX(); // calls draw coordinate box function
drawBRICKS(); //calls the function to draw the boxes
//have we hit a brick?
rowheight = brickheight + padding;
colwidth = brickwidth + padding;
row = Math.floor(y / rowheight);
col = Math.floor(x / colwidth);
//if so, reverse the ball and mark the brick as broken
if (y < numrows * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy;
bricks[row][col] = 0;
}
if (x + dx > WIDTH || x + dx < 0) dx = -dx;
if (y + dy < 0) dy = -dy;
else if (y + dy > ((HEIGHT - paddleh) - ppoffset) || y + dy > HEIGHT) {
if (x > paddlex && x < paddlex + paddlew)
//switch! once first is true, then second goes
dy = -dy;
else if (y + dy > ((HEIGHT - paddleh) - ppoffset) && y + dy > HEIGHT) {
clearInterval(intervalId);
}
}
x += dx;
y += dy;
if (rightpress) paddlex += 5;
else if (leftpress) paddlex -= 5;
}
function clear() {
Cir.clearRect(0, 0, WIDTH, HEIGHT);
//Is this jquery? I suspect this part of the code making the circle rendering fail.
}
start();
init_paddle();
initbricks();
Ages ago I wrote a similar code in pure JavaScript here
this code uses pure javascript and no library.The code is well commented(I think :))
I generally attached events like this
document.onkeydown = function(e)
{
e = e || window.event;
switch (e.keyCode) { // which key was pressed?
case 32: // release ball.
if(!game.ball.isFree)
{
game.ball.isFree = true;
game.ball.directionX = game.ball.directionY = 1;
game.ball.x = game.ball.offsetLeft;
game.ball.y = game.screen.offsetHeight - game.ball.offsetTop;
}
break;
case 37: // left, rotate player left
game.bar.direction = -1;
break;
case 39: // right, rotate player right
game.bar.direction = 1;
break;
}
}
document.onkeyup = function(e)
{
e = e || window.event;
switch (e.keyCode)
{
case 37:
case 39:
game.bar.direction = 0;
break;
}
}
},
Ofcourse you have many other places which might need porting so a helpful break down of questions would be easier to answer :)
Hope this helps

Bouncing Ball Game, Mouse Detect Event, JavaScript

I've already created a bouncing ball which bounces off the walls of the HTML5 Canvas that I have specified.
My goal is to make a "Game Over" screen appear when the pointer (mouse) hovers over the ball.
I have already searched and found some tutorials on mouse events in Javascript, but I'm not really sure how to implement them into my code =/.
Any help would be amazing.
<script>
var x = Math.floor((Math.random() * 600) + 1);
var y = Math.floor((Math.random() * 300) + 1);
var dx = 2;
var dy = 4;
function begin()
{
gameCanvas = document.getElementById('gameCanvas');
context = gameCanvas.getContext('2d');
return setInterval (draw, 20);
}
begin();
function draw()
{
context.clearRect(0,0,600,300);
context.fillStyle = "#0000FF";
context.beginPath();
context.arc(x,y,80,0,Math.PI*2,true);
context.closePath();
context.fill();
if (x < 0 || x > 600) dx=-dx
if (y < 0 || y > 300) dy=-dy;
x += dx;
y += dy;
}
gameCanvas.onmousemove = function (e)
{
var gameCanvas = e.target;
var context = gameCanvas.getContext('2d');
var coords = RGraph.getMouseXY(e);
}
You need to check if the mouse is hovering over the ball (hit test) by checking the distance of the ball to the cursor. If the distance is smaller than radius of the ball, it means that the mouse is over the ball.
Note, that you need to adjust the code below to your needs
Example:
var mouse_x = 10, mouse_y = 10, ball_x = 10, ball_y = 10, ball_radius = 70, is_game_over = false
if( Math.sqrt( Math.pow( mouse_x - ball_x, 2 ) + Math.pow( mouse_x - ball_x, 2 )) < ball_radius && !is_game_over ) {
console.log('Cursor is over the mouse, game over')
is_game_over = true
}
Do it for every frame update.
you can add onmousemove=SetValues() to your body element like so:
<body onmousemove=SetValues()>
and change your code to this:
<script>
var x = Math.floor((Math.random() * 600) + 1);
var y = Math.floor((Math.random() * 300) + 1);
var dx = 2;
var dy = 4;
var mouseX;
var mouseY;
function setValues(e)
{
mouseX = e.pageX; //get mouse x
mouseY = e.pageY; //get mouse y
}
function begin()
{
gameCanvas = document.getElementById('gameCanvas');
context = gameCanvas.getContext('2d');
return setInterval (draw, 20);
}
begin();
function draw()
{
context.clearRect(0,0,600,300);
context.fillStyle = "#0000FF";
context.beginPath();
context.arc(x,y,80,0,Math.PI*2,true);
context.closePath();
context.fill();
if (x < 0 || x > 600) dx=-dx
if (y < 0 || y > 300) dy=-dy;
x += dx;
y += dy;
//check if the mouse is on the ball
var centerX = x + 80; //center of ball
var centerY = y; //center of ball
if(Math.pow((mouseX - centerX), 2) + Math.pow((mouseY - centerY), 2) <= 6400){
//do whatever to end game
}
}

Categories