Reputation: 6662
I want to get the cyan dot spin around in the canvas chasing my mouse, but like my mouse has gravity. Think of it like the mouse is a planet and the object is a comet. I tried this code, but it just makes the cyan dot spin like crazy and not follow the mouse too much.
<div class="section">
<div id="intro">
<div id="mouse" style="border-radius: 50%; position: absolute;height: 20px;width: 20px;background-color: blue;"></div>
<canvas id="canvas" style="background:black;">
</canvas>
<script>
var canvas = document.getElementById("canvas");
canvas.width = $(window).width();
canvas.height = $(window).height();
</script>
<script>
var canvas = document.querySelector("#canvas")
var ctx = canvas.getContext("2d");
var mouseX;
var mouseY;
var kule = {
cx : 100,
cy : 100,
vy : 2,
vx : 2,
r : 5,
e : 1,
color : "cyan"
};
function draw() {
var image = new Image();
image.src = "Player.png";
ctx.drawImage(image, 100, 100);
var boundsX = canvas.width;
var boundsY = canvas.height;
//ctx.clearRect(0, 0, bounds, bounds);
ctx.fillStyle = kule.color;
ctx.beginPath();
ctx.arc(kule.cx, kule.cy, kule.r, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
var deltaX = mouseX - kule.cx;
var deltaY = mouseY - kule.cy;
kule.vy = kule.vy + deltaX/1000;
kule.vx = kule.vx + deltaY/1000;
kule.cx = kule.cx + kule.vx;
kule.cy = kule.cy + kule.vy;
if (kule.cy + kule.r >= boundsY) {
kule.vy = -kule.vy * kule.e;
kule.vy = -(Math.abs(kule.vy)) * kule.e;
}
if (kule.cx + kule.r >= boundsX) {
kule.vx = -kule.vx * kule.e;
kule.vx = -(Math.abs(kule.vx)) * kule.e;
}
if (kule.cy - kule.r <= 0) {
kule.vy = kule.vy * kule.e;
kule.vy = (Math.abs(kule.vy)) * kule.e;
}
if (kule.cx - kule.r <= 0) {
kule.vx = kule.vx * kule.e;
kule.vx = (Math.abs(kule.vx)) * kule.e;
}
}
setInterval(draw, 10);
$(document).on("mousemove",function(event){
mouseX = event.pageX;
mouseY = event.pageY;
$("#mouse").animate(
{
left:mouseX-10,
top:mouseY-10
},0)});
</script>
</div>
Upvotes: 0
Views: 2147
Reputation: 4833
I removed some pieces of your code to simplify my answer, but here's the idea :
var startTime = (new Date()).getTime();
var rotationSpeed = 500; // Milliseconds for a full turn
var orbitRadius = 75;
function draw() {
var boundsX = canvas.width;
var boundsY = canvas.height;
ctx.clearRect(0, 0, boundsX, boundsY);
ctx.fillStyle = kule.color;
var currentTime = (new Date()).getTime();
var passedTime = currentTime - startTime;
var angle = Math.PI * 2 * (passedTime / rotationSpeed);
ctx.beginPath();
ctx.arc(mouseX + Math.cos(angle) * orbitRadius, mouseY + Math.sin(angle) * orbitRadius, kule.r, 0, Math.PI * 2);
ctx.fill();
}
Upvotes: 4