please explain how to implement this script on my animation - javascript

I have an animation that i am building, it´s done with adobe animate and the graphics are fine but the code is not working or i just dont understand how it works.
This code adds pan,zoom and centering controls over a given map. The problem is that my map is much bigger than the canvas stage and if i pan or zoom it too much the map borders come inside the stage and though revealing the background of the stage which i don´t want. I need the stage to act as a mask and make the map visible but not allow it to go outside the map borders.
Is there an easy way to adapt the code below to what I need?
var that = this;
var clickedX;
var clickedY;
var isDragging = false;
var friction = 0.85;
var speedX = 0;
var speedY = 0;
var mapOriginalX = this.map.x;
var mapOriginalY = this.map.y;
var mapNudge = 5;
var minScale = 0.3;
var maxScale = 3;
console.log(this.map.x);
console.log(this.map.y);
console.log(stage.x);
console.log(stage.y);
function onMouseWheel(e)
{
var delta;
if (e == window.event)
delta = -10 / window.event.wheelDeltaY;
else
delta = e.detail / 30;
var zoomFactor = delta;
scaleMap(zoomFactor);
}
function mouseDown(e)
{
clickedX = stage.mouseX;
clickedY = stage.mouseY;
isDragging = true;
}
function stageMouseUp(e)
{
isDragging = false;
}
function update(e)
{
if (isDragging)
{
speedX = stage.mouseX - clickedX;
speedY = stage.mouseY - clickedY;
}
speedX *= friction;
speedY *= friction;
that.map.x += speedX;
that.map.y += speedY;
clickedX = stage.mouseX;
clickedY = stage.mouseY;
}
function resetMap()
{
that.map.x = mapOriginalX;
that.map.y = mapOriginalY;
that.map.scaleX = that.map.scaleY = 1;
}
function zoomMap(e)
{
if (e.currentTarget == that.plusButton)
scaleMap(-0.1);
if (e.currentTarget == that.minusButton)
scaleMap(0.1);
}
function moveMap(e)
{
if (e.currentTarget == that.upButton)
speedY -= mapNudge;
else if (e.currentTarget == that.rightButton)
speedX += mapNudge;
else if (e.currentTarget == that.downButton)
speedY += mapNudge;
else if (e.currentTarget == that.leftButton)
speedX -= mapNudge;
}
function scaleMap(amount)
{
var map = that.map;
map.scaleX -= amount;
map.scaleY = map.scaleX;
if (map.scaleX < minScale)
map.scaleX = map.scaleY = minScale;
else if (map.scaleX > maxScale)
map.scaleX = map.scaleY = maxScale;
}
// listeners
this.map.on("mousedown", mouseDown.bind(this));
this.resetButton.on("click", resetMap.bind(this));
this.plusButton.on("click", zoomMap.bind(this));
this.minusButton.on("click", zoomMap.bind(this));
this.upButton.on("click", moveMap.bind(this));
this.rightButton.on("click", moveMap.bind(this));
this.downButton.on("click", moveMap.bind(this));
this.leftButton.on("click", moveMap.bind(this));
stage.on("stagemouseup", stageMouseUp.bind(this));
document.getElementById('canvas').addEventListener('mousewheel', onMouseWheel.bind(this));
document.getElementById('canvas').addEventListener('DOMMouseScroll', onMouseWheel.bind(this));
createjs.Ticker.addEventListener("tick", update.bind(this));
resetMap();

Related

How would do I get the paddle to hit the ball up and back into the air?

var BALL_RADIUS = 15;
var STARTING_Y = 0;
var STARTING_X = 150;
var GRAVITY_ACCELERATION = 2;
var ANIMATION_DELAY = 60;
var square;
var paddlelocationX = 100;
var paddlelocationY = 410;
var score = 0;
var ball;
var velocityX;
var velocityY;
function start(){
var start = println("Welcome to the game Ping Ball ");
createBall();
initializeVelocity();
startSimulation();
square = new Rectangle(90, 10);
//I messed around with the Y-Variable a slight bit
square.setPosition(paddlelocationX, paddlelocationY);
add(square);
keyDownMethod(keyDown);
}
function createBall(){
ball = new Circle(BALL_RADIUS);
ball.setPosition(STARTING_X, STARTING_Y);
add(ball);
}
function initializeVelocity(){
velocityX = Randomizer.nextFloat(0, 5);
velocityY = 0;
}
function startSimulation(){
setTimer(moveBall, ANIMATION_DELAY);
}
function moveBall(){
ball.move(velocityX, velocityY);
checkForBounce();
velocityY += GRAVITY_ACCELERATION;
}
function checkForBounce(){
var radius = ball.getRadius();
if(ball.getX() + radius >= getWidth()){
velocityX *= -1;
ball.setPosition(getWidth() - radius, ball.getY());
}
if(ball.getX() - radius <= 0){
velocityX *= -1;
ball.setPosition(radius, ball.getY());
}
if(ball.getY() + radius >= getHeight()){
velocityY = -1 * Math.abs(velocityY);
ball.setPosition(ball.getX(), getHeight() - radius);
}
if(ball.getY() - radius <= 0){
velocityY *= -1;
ball.setPosition(ball.getX(), radius);
}
if(ball.getY() >= 460){
ball.setPosition(ball.getX(), 500);
}
}
function keyDown(e){
if(e.keyCode == Keyboard.LEFT){
square.move(-10, 0);
}
if(e.keyCode == Keyboard.RIGHT){
square.move(10, 0);
}
}
var txt = new Text("Current Score:"+score,"10pt Ariel");
txt.setPosition(312,13);
add(txt);
So far this is my code made. I'm really struggling to find out where I can implement something to get the ball to hit the paddle and I don't know where to start. Like, I know I that if the ball's center comes near the paddle then I know I need the ball to bounce up from there and keep on bouncing back in forth just like that.
I don't know if I need to add that conditionality under my "checkBounce" function or make a new one.
Thanks for anyone who can help <3
Also, the code mainly only works in CodeHS (Javascript Graphics)

Adding Gravity to Animations

I'm trying to understand how to add some physics like gravity and wind into my animations. I can't quite wrap my head around how to make this ball bounce as if it has gravity... each update I am accumulating the forces, applying it to the velocity, then clearing the forces. But the only way I can think to make it bounce back up is to change the Y direction..but then it just keeps going until it hits the top. Is there something obvious I'm missing? Any advice is appreciated. Thanks for reading
var C, canvas, context = null;
var gravity = {x:0, y:1};
var wind = {x:0.4, y:0};
var height = 140;
var width = 300;
function Ball(x,y,w,h) {
var ball = this;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.xVelocity = 0;
this.yVelocity = 0;
this.xDirection = 1;
this.yDirection = 1;
this.update = function() {
ball.applyForce(gravity);
//ball.applyForce(wind);
ball.x += (ball.xVelocity * ball.xDirection);
ball.y += (ball.yVelocity * ball.yDirection);
if((ball.x + ball.w) >= width) {
//ball.xDirection = -1;
ball.x = width - ball.w / 2 ;
ball.xVelocity = -ball.xVelocity
} else if(ball.x <= 0) {
//ball.xDirection = 1;
ball.xVelocity = ball.xVelocity
}
if((ball.y + ball.h) >= height) {
//ball.yDirection = -1;
ball.y = height - ball.w;
ball.yVelocity = -ball.yVelocity
} else if(ball.y <= 0) {
//ball.yDirection = 1;
ball.yVelocity = ball.yVelocity
}
//ball.clearForces();
}
this.draw = function() {
context.beginPath();
context.arc(ball.x,ball.y,ball.w,0,2*Math.PI);
context.stroke();
}
this.applyForce = function(force) {
ball.xVelocity += force.x;
ball.yVelocity += force.y;
}
this.clearForces = function(force) {
ball.xVelocity = 0;
ball.yVelocity = 0;
}
}
function Canvas( ) {
var CV = this;
var balls = new Array();
balls.push(new Ball(100, 10, 10, 10));
this.loop = function() {
CV.update();
CV.draw();
window.requestAnimationFrame(CV.loop);
}
this.update = function() {
for(var i=0; i<balls.length; i++) {
balls[i].update();
}
}
this.draw = function() {
context.clearRect(0, 0, width, height);
for(var i=0; i<balls.length; i++) {
balls[i].draw();
}
}
}
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
C = new Canvas( );
C.loop();
#canvas {border:1px solid #d4d4d4; }
<canvas id="canvas" width="300" height="140"></canvas>
In kinematics, simple motion can sometimes be expressed as v(t) = aΔt where v is velocity at t seconds and aΔt is the acceleration times the interval Δt.
A way to simulate this could be to either calculate the ball.yVelocity component as (-someAcceleration) * someTimeIndex or to preform a function like
var ball.yVelocity = ball.yVelocity - someFactor each loop.
EDIT 1: I would also set up a separate variable likeyVelocityAbs in order to handle the magnitude of ball.yVelocity so as not to screw up your direction each time the ball bounces. Good luck!
EDIT 2: Try updating your clearForces() function like this:
this.clearForces = function(force) {
ball.xVelocity = 0;
//ball.yVelocity = 0;
}
It should work! Albeit a fairly janky representation, the simulation should fit better. I would suggest adding some functionality that resets the ball, though.

Detecting Collision of two sprites in arrays? Javascript

I have been reading/searching for an answer to detect collisions of sprites in two arrays. I am not understanding how to pass two arrays into the detection function and have it check all contents of each array against each other. Any input would be greatly appreciated.
<script type="text/javascript">
var FIRE = 0;
var NORTH = 38;
var SOUTH = 40;
var EAST = 39;
var WEST = 37;
var destX = 350;
var destY = 500;
var canvas = null;
var context = null;
var sprites = null;
var player = null;
var island = null;
var enemies = [];
var fires = [];
var gameLoopInterval = null;
var offScreenFire = null;
var isShooting = false;
var intersect = null;
var Fire = function() {
this.spriteX = 278;
this.spriteY = 110;
this.spriteWidth = 13;
this.spriteHeight = 16;
this.destX = player.destX + 25;
this.destY = player.destY;
this.speed = 5;
}
var Player = function(name) {
this.name = name;
this.spriteX = 5;
this.spriteY = 400;
this.spriteWidth = 64;
this.spriteHeight = 64;
this.destX = 350;
this.destY = 500;
this.speed = 5;
this.level = 1;
}
var Enemy = function() {
this.spriteX = 4;
this.spriteY = 4;
this.spriteWidth = 32;
this.spriteHeight = 32;
this.destX = Math.ceil(Math.random() * (800 - this.spriteWidth));
this.destY = this.spriteWidth;
this.speed = Math.ceil(Math.random() * 5);
}
var Island = function() {
this.spriteX = 168;
this.spriteY = 500;
this.spriteWidth = 64;
this.spriteHeight = 64;
this.destX = Math.ceil(Math.random() * (800 - this.spriteWidth));
this.destY = this.spriteWidth - 64;
this.speed = 2;
}
Fire.prototype.takeTurn = function() {
var intersect;
var projdestX = this.destX;
var projdestY = this.destY;
var projspriteWidth = this.spriteWidth;
var projspriteHeight = this.spriteHeight;
for (enemy in enemies) {
intersect = intersect || intersects(enemy.destX, enemy.destY, enemy.spriteWidth, enemy.spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
}
if(intersect == true) { alert("colliding"); }
else{drawImage(this);}
// if (intersect != true){
// drawImage(this);
// }
// else {
// alert("boom");
// }
if(this.destY <= 0){
offScreenFire = fires.indexOf(this);
fires.splice(offScreenFire, 1);
}
else
this.destY -= this.speed;
}
Player.prototype.takeTurn = function() {
drawImage(this);
}
Enemy.prototype.takeTurn = function() {
drawImage(this);
if (this.destY < canvas.height)
this.destY += this.speed;
else
this.destY = -32;
}
Island.prototype.takeTurn = function() {
drawImage(this);
this.destY += this.speed;
}
function fireAction() {
var fire = new Fire();
drawImage(fire);
fires.push(fire);
}
function drawImage(sprite) {
context.drawImage(sprites, sprite.spriteX, sprite.spriteY, sprite.spriteWidth, sprite.spriteHeight, sprite.destX, sprite.destY, sprite.spriteWidth, sprite.spriteHeight );
}
function gameLoop () {
context.clearRect(0, 0, canvas.width, canvas.height);
island.takeTurn();
player.takeTurn();
//console.log(fires); //debug
for (fire in fires) {
fires[fire].takeTurn();
}
for (enemy in enemies) {
enemies[enemy].takeTurn();
}
}
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
if (w2 !== Infinity && w1 !== Infinity) {
w2 += x2;
w1 += x1;
if (isNaN(w1) || isNaN(w2) || x2 > w1 || x1 > w2)
return false;
}
if (y2 !== Infinity && h1 !== Infinity) {
h2 += y2;
h1 += y1;
if (isNaN(h1) || isNaN(y2) || y2 > h1 || y1 > h2)
return false;
}
return true;
}
window.onload = function() {
//alert('here');
canvas = document.getElementById('gameWorld');
context = canvas.getContext("2d");
sprites = new Image();
player = new Player('Brad');
island = new Island();
sprites.onload = function() {
drawImage(player);
for (i = 0; i < 3; i++) {
var enemy = new Enemy();
drawImage(enemy);
enemies.push(enemy);
}
}
sprites.src = "Sprites/1945.png";
gameLoopInterval = setInterval('gameLoop()', 100)
}
window.onkeypress = function(e){
var evt = window.event ? event : e;
//alert(evt.keyCode);
switch(evt.keyCode) {
case NORTH:
if (player.destY > 0)
player.destY -= player.speed;
else
player.destY == player.destY;
break;
case SOUTH:
if (player.destY < canvas.height - player.spriteWidth)
player.destY += player.speed;
else
player.destY == player.destY;
break;
case EAST:
if (player.destX < canvas.width - player.spriteWidth)
player.destX += player.speed;
else
player.destX == player.destY;
break;
case WEST:
if (player.destX > 0)
player.destX -= player.speed;
else
player.destX == player.destX;
break;
case FIRE:
fireAction();
break;
}
}
</script>
Your problems seems to be in:
for (enemy in enemies) {
intersect = intersects(enemy.destX, enemy.destY, enemy.spriteWidth, enemy.spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
}
intersect will always have the last value saved. (Meaning you are really only checking if it intersects with the last enemy.)
A quick solution would be to change the inner line to:
intersect = intersect || intersects(enemy.destX, enemy.destY, enemy.spriteWidth, enemy.spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
This will make intersect stay as true if the fire doesn't intersect with the next enemy.
Edit:
Your second problem is in the same for(). In javascript, when you do a for in, the first variable does not have a reference to the instance, but rather is only the key.
Your final for should look like:
for (enemy in enemies) {
intersect = intersect || intersects(enemies[enemy].destX, enemies[enemy].destY, enemies[enemy].spriteWidth, enemies[enemy].spriteHeight, projdestX, projdestY, projspriteWidth, projspriteHeight);
}
You also seem to not be spawning any enemies. In my fiddle of your code (http://jsfiddle.net/path411/umjnQ/) I added the following snippet into your gameLoop():
if(enemies.length < 1) {
enemies.push(new Enemy());
}
This simply creates a new enemy if you don't already have one. (You will probably want to change later).

Using EaselJS sprite sheet in existing code

I want to modify existing code which uses an image to animate, and use a sprite sheet instead. I'm using the EaselJS library for this.
The piece of code that creates the objects for animation:
function initStageObjects(){
car = new Car('img/car.png',canvas.width()/2,canvas.height()/2);
}
And this is the complete code:
$(window).load(function(){
$(document).ready(function(){
// Canvas Variables
var canvas = $('#canvas');
var context = canvas.get(0).getContext('2d');
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
// Keyboard Variables
var leftKey = 37;
var upKey = 38;
var rightKey = 39;
var downKey = 40;
// Keyboard event listeners
$(window).keydown(function(e){
var keyCode = e.keyCode;
if(keyCode == leftKey){
car.left = true;
} else if(keyCode == upKey){
car.forward = true;
} else if(keyCode == rightKey){
car.right = true;
} else if (keyCode == downKey){
car.backward = true;
}
});
$(window).keyup(function(e){
var keyCode = e.keyCode;
if(keyCode == leftKey){
car.left = false;
} else if(keyCode == upKey){
car.forward = false;
} else if(keyCode == rightKey){
car.right = false;
} else if (keyCode == downKey){
car.backward = false;
}
});
// Start & Stop button controlls
var playAnimation = true;
var startButton = $('#startAnimation');
var stopButton = $('#stopAnimation');
startButton.hide();
startButton.click(function(){
$(this).hide();
stopButton.show();
playAnimation = true;
updateStage();
});
stopButton.click(function(){
$(this).hide();
startButton.show();
playAnimation = false;
});
// Resize canvas to full screen
function resizeCanvas(){
canvas.attr('width', $(window).get(0).innerWidth);
canvas.attr('height', $(window).get(0).innerHeight);
canvasWidth = canvas.width();
canvasHeight = canvas.height();
}
resizeCanvas();
$(window).resize(resizeCanvas);
function initialise(){
initStageObjects();
drawStageObjects();
updateStage();
}
// Car object and properties
function Car(src, x, y){
this.image = new Image();
this.image.src = src;
this.x = x;
this.y = y;
this.vx = 0;
this.vy = 0;
this.angle = 90;
this.topSpeed = 5;
this.acceleration = 0.1;
this.reverse = 0.1;
this.brakes = 0.3;
this.friction = 0.05;
this.handeling = 15;
this.grip = 15;
this.minGrip = 5;
this.speed = 0;
this.drift = 0;
this.left = false;
this.up = false;
this.right = false;
this.down = false;
}
// Create any objects needed for animation
function initStageObjects(){
car = new Car('img/car.png',canvas.width()/2,canvas.height()/2);
}
function drawStageObjects(){
context.save();
context.translate(car.x,car.y);
context.rotate((car.angle + car.drift) * Math.PI/180);
context.drawImage(car.image, -25 , (-47 + (Math.abs(car.drift / 3))));
// context.fillRect(-5, -5, 10, 10);
context.restore();
}
function clearCanvas(){
context.clearRect(0, 0, canvasWidth, canvasHeight);
context.beginPath();
}
function updateStageObjects(){
// Faster the car is going, the worse it handels
if(car.handeling > car.minGrip){
car.handeling = car.grip - car.speed;
}
else{
car.handeling = car.minGrip + 1;
}
// Car acceleration to top speed
if(car.forward){
if(car.speed < car.topSpeed){
car.speed = car.speed + car.acceleration;
}
}
else if(car.backward){
if(car.speed < 1){
car.speed = car.speed - car.reverse;
}
else if(car.speed > 1){
car.speed = car.speed - car.brakes;
}
}
// Car drifting logic
if(car.forward && car.left){
if(car.drift > -35){
car.drift = car.drift - 3;
}
}
else if(car.forward && car.right){
if(car.drift < 35){
car.drift = car.drift + 3;
}
}
else if(car.forward && !car.left && car.drift > -40 && car.drift < -3){
car.drift = car.drift + 3;
}
else if(car.forward && !car.right && car.drift < 40 && car.drift > 3){
car.drift = car.drift - 3;
}
if(car.drift > 3){
if(!car.forward && !car.left){
car.drift = car.drift - 4;
}
}
else if(car.drift > -40 && car.drift < -3){
if(!car.forward && !car.right){
car.drift = car.drift + 4;
}
}
// General car handeling when turning
if(car.left){
car.angle = car.angle - (car.handeling * car.speed/car.topSpeed);
} else if(car.right){
car.angle = car.angle + (car.handeling * car.speed/car.topSpeed);
}
// Use this div to display any info I need to see visually
$('#stats').html("Score: 0");
// Constant application of friction / air resistance
if(car.speed > 0){
car.speed = car.speed - car.friction;
} else if(car.speed < 0) {
car.speed = car.speed + car.friction;
}
// Update car velocity (speed + direction)
car.vy = -Math.cos(car.angle * Math.PI / 180) * car.speed;
car.vx = Math.sin(car.angle * Math.PI / 180) * car.speed;
// Plot the new velocity into x and y cords
car.y = car.y + car.vy;
car.x = car.x + car.vx;
}
// Main animation loop
function updateStage(){
clearCanvas();
updateStageObjects();
drawStageObjects();
if(playAnimation){
setTimeout(updateStage, 25);
}
}
// Initialise the animation loop
initialise();
});
});//]]>
// JavaScript Document
How could i replace the image being used by the sprite i created?
Even though you maybe could implement a createjs.SpriteSheet into a non-Createjs/non-EaselJS project I would strongly recommend you not to do that, EaselJS-classes where not designed to be used as single modular classes in any kind of project, they best work together in the framework. In the end you probably will need more time and probably end up with more code by trying get everything to work than with just converting your (yet still small) project to EaselJS all together. So learn something new today and refacture your project to EaselJS ;-)
but if you want more work, continue reading:
A createjs.SpriteSheet basically only handles SpriteSheet data and you can use mySpriteSheet.getFrame(int); to get the image and the source-rect to that frame so you can draw it to your canvas. But a SpriteSheet alone won't handle animations for you, so you would have to advance the "playhead" every frame yourself(go back to frame 0 if at the end ect...), or you can implement another createjs-class called createjs.BitmapAnimation - however, drawing this to your canvas would again require additional code or yet an additional createjs-class: you see where this is getting.

How do I make an object change it's direction smoothly?

I have a simple Javascript program that displays a small rectangle in a canvas. The rectangle moves towards the mouse position. When it changes direction, it does so with sharp corners. As in, if the rectangle left a line behind, when I move my mouse in a circle, the rectangle would draw a tilted square.
What I'd want to happen, is that it would draw a circle. No sharp corners.
Here's the code I am using for changing the direction:
function changeDir()
{
if(mouseXCoord-5<x && x<mouseXCoord+5)
{
xDirection = 0;//stop moving if close to mouse
}
else if(x>mouseXCoord)
{
xDirection = -1;
}
else if(x<mouseXCoord)
{
xDirection = 1;
}
if(mouseYCoord-5<y && y<mouseYCoord+5)
{
yDirection = 0;//stop moving if close to mouse
}
else if(y>mouseYCoord)
{
yDirection = -1;
}
else if(y<mouseYCoord)
{
yDirection = 1;
}
}
The draw function:
function draw()
{
context2D.clearRect(0, 0, canvas.width, canvas.height);
fillwith = context2D.fillStyle='red';
context2D.fillRect(x,y,10,10);
changeDir();
x = x + (thrust * xDirection);
y = y + (thrust * yDirection);
console.log(x,y,xDirection, yDirection,mouseXCoord,mouseYCoord);
}
So, how do I do that?
Update:
I changed the changeDir() function so that it makes the corners of the tilted square rounded.
function changeDir()
{
if(mouseXCoord-5<x && x<mouseXCoord+5)
{
xstop = true;//stop moving if close to mouse
}
else if(x>mouseXCoord)
{
if(Math.abs(xthrust)==mainThrust)
{
xthrust = -1*mainThrust;
}
else
{
xthrust--;
}
xstop = false;//make sure it moves
}
else if(x<mouseXCoord)
{
if(xthrust==mainThrust)
{
xthrust = mainThrust;
}
else
{
xthrust++;
}
xstop = false;//make sure it moves
}
if(mouseYCoord-5<y && y<mouseYCoord+5)
{
ystop = true;//stop moving if close to mouse
}
else if(y>mouseYCoord)
{
if(Math.abs(ythrust)==mainThrust)
{
ythrust = -1*mainThrust;
}
else
{
ythrust--;
}
ystop = false;//make sure it moves
}
else if(y<mouseYCoord)
{
if(ythrust==mainThrust)
{
ythrust = mainThrust;
}
else
{
ythrust++;
}
ystop = false;//make sure it moves
}
}
Here's the variables I declare:
const FPS = 5;
var x = 300;
var y = 200;
var xDirection = 1;
var yDirection = 1;
var image = new Image();
var canvas = null;
var context2D = null;
var mouseXCoord = 0;
var mouseYCoord = 0;
var mainThrust = 5;
var xthrust = mainThrust;
var ythrust = mainThrust;
var xstop = false;
var ystop = false;
Where it actualy moves:
changeDir();
if(!xstop)
x = x + (xthrust);
if(!ystop)
y = y + (ythrust);
Ok, here's my new code thanks to cape1232. I actually started over entirely. I get smooth turning, but the speed the block moves at changes. Demo at: http://develzone.davidreagan.net/jsMoveTesting/index.html
var gameVars = {
fps: 30
}
var object = {
name: 'default',
xpos: 200,
ypos: 200,
xVect: 1,
yVect: 1,
thrust: 15
}
ctx = null;
canvas = null;
xMousePos = 0;
yMousePos = 0;
runGame = null;
function init()
{
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
$('#canvas').mousemove(getMousePos);
$('#canvas').click(stop);
//setTimeout('clearInterval(runGame);',30000);
}
function start()
{
runGame = setInterval('run();',1000/gameVars.fps);
}
function run()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveBlock();
//ctx.translate(object.xpos,object.ypos);
drawBlock();
showMousePos = 'X: ' + xMousePos + ' Y: ' + yMousePos;
ctx.fillText(showMousePos, 215,50);
}
function stop()
{
//alert('hit stop');
console.log('clicked');
//if(e.keyCode == 113)
if(runGame)
{
clearInterval(runGame);
runGame = false;
//console.log('stop true');
}
else
start();
}
function drawBlock()
{
ctx.fillRect(object.xpos,object.ypos,10,10);
}
function moveBlock()
{
xDiff = xMousePos - object.xpos;
yDiff = yMousePos - object.ypos;
minDiff = Math.max(Math.min(xDiff, yDiff), 1);
deltaX = xDiff / minDiff;
deltaY = yDiff / minDiff;
// Scale the deltas to limit the largest to mainThrust
maxDelta = Math.max(Math.max(deltaX, deltaY), 1)
if (maxDelta>object.thrust)
{
deltaX = deltaX * object.thrust / maxDelta;
deltaY = deltaY * object.thrust / maxDelta;
}
if(object.xpos >= canvas.width)
{
object.xpos = 0;
}
else
{
object.xpos += deltaX;
//console.log('moveBlock xpos else: '+object.xpos);
}
if(object.ypos >= canvas.height)
{
object.ypos = 0;
}
else
{
object.ypos += deltaY;
//console.log('moveBlock ypos else: '+object.ypos);
}
console.log('xpos: '+object.xpos);
console.log('ypos: '+object.ypos);
console.log('xMousePos: '+xMousePos);
console.log('yMousePos: '+yMousePos);
console.log('xDiff: '+xDiff);
console.log('yDiff: '+yDiff);
console.log('minDiff: '+minDiff);
console.log('deltaX: '+xDiff+'/'+minDiff+ ' = '+ deltaX);
console.log('deltaY: '+yDiff+'/'+minDiff+ ' = '+ deltaY);
console.log('maxDelta: '+maxDelta);
}
function getMousePos(e)
{
xMousePos = e.pageX;
yMousePos = e.pageY;
//console.log('Mouse Moved');
}
window.onload = init;
You don't want your xDirection and yDirection to be only 1 or -1. They need to be proportional to the difference between the mouse and the rectangle position.
Edited to take comments into account.
function changeDir()
{
xDiff = mouseXCoord - x;
yDiff = mouseYCoord - y;
// Scale the smallest diff to be 1 (or less)
minDiff = max(min(xDiff, yDiff), 1);
deltaX = xDiff / minDiff;
deltaY = yDiff / minDiff;
// Scale the deltas to limit the largest to mainThrust
maxDelta = max(max(deltaX, deltaY), 1)
if (maxDelta>mainThrust)
{
deltaX = deltaX * mainThrust / maxDelta;
deltaY = deltaY * mainThrust / maxDelta;
}
if(mouseXCoord-5<x && x<mouseXCoord+5)
{
xDirection = 0;//stop moving if close to mouse
}
else
{
xDirection = deltaX;
}
if(mouseYCoord-5<y && y<mouseYCoord+5)
{
yDirection = 0;//stop moving if close to mouse
}
else
{
yDirection = deltaY;
}
}
Instead of having xDirection and yDirection (the sine and cosine of your direction, actually) sharply defined as 0, 1, or -1, you need to define more precisely the direction you should eventually be heading in, and recall what direction you were last moving in and how many "angular steps" you've done in changing the direction from what was to what it should be.
How many such angular steps you want to take for a change of direction, and whether each step should be of the same size or depend on how fast you're moving and/or how brusquely you're swerving, etc, is something you should adapt by trial and error, since it appears that what you're mostly after is to have things "look" right, so it's hard to give a precise prescription (for what looks right to you;-).

Categories

Resources