Puppe
Puppe

Reputation: 122

How to make HTML canvas objects move with a cursor and slow down over time?

I am new to JavaScript and currently working on small 2d game, where in a html canvas element, I have drawn a puck and a small goal line, and the point of the "game" is to throw the puck to the goal. My problem currently is that I just do not know how to make the puck move with my mouse controls. I've tried to use this as reference to a lot of the code, but it seems like I'm struggling to impltement other stuff in to my own code.

Here's a part of my code as well. The part that currently takes control of the puck

document.addEventListener("mousedown", mouseDownHandler, false);
// When user clicks, the puck starts following the cursor
function mouseDownHandler(e) {

dx = 0;
dy = 0;
document.addEventListener("mousemove", mousemoveHandler, false);
document.addEventListener("mouseup", mouseUpHandler, false);
function mousemoveHandler(e) {
var relativeX = e.clientX - canvas.offsetLeft;
var relativeY = e.clientY - canvas.offsetTop;
if (relativeX > 0 && relativeX < canvas.width) {
  x = relativeX - 18 / 2;
} if (relativeY > 0 && relativeY < canvas.height) {
  y = relativeY - 20 / 2;
}
}
function mouseUpHandler(e) {
  dx = -dx + 1;
  dy = -dy - 1;
  x += 0;
  y += 0;
  document.removeEventListener("mousemove", mousemoveHandler, false);
 }
}

And then my variables:

// Variables used
var canvas = document.getElementById("gameArea");
var ctx = canvas.getContext("2d");


// Coordinates used for the puck
var x = canvas.width/2;
var y = canvas.height/2;
// Coordinates used to make the puck "move" as a placeholder"
var dx = 0;
var dy = 0;

// Gives the puck a radius that is used for calculations
var puckRadius = 10;
var goalieRadius = 57;

// Variables for goalie
var z = canvas.width/2;
var a = 5;

//variable for counting score
var score = 0;

// Variables for goal size and location
var goalHeight = 10;
var goalWidth = 115;
var goalX = (canvas.width-goalWidth)/2;

Tell me if you need anything more and thank you in advance!

Edit: https://jsfiddle.net/6gn48dbq/1/ Also a Jfiddle of the work!

Upvotes: 2

Views: 859

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17594

So following up on my comment...

You need to add the speed in your mouse:

function mouseUpHandler(e) {
  dx = -dx + speed;
  dy = -dy - speed;

...and later that speed could be controlled by a slider <input type="range"> fun fun

And on every pass of the draw you apply the friction:

function draw() {
  dx *= friction;
  dy *= friction;

Here is a working example:
https://jsfiddle.net/nfdyLv61/

Upvotes: 1

Related Questions