Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give my javascript ball a rolling animation when it moves?

I have the following HTML code:

<img src="game_files/ball.png" id="ball" /> It's a div containing an image of a ball (top view of a ball)

This ball I can move with my arrow keys and some javacript to go up, left, right, down, etc etc. I do this with this code:

var ball = function  () {
    var inited = false,
        el,
        xcheck = 50,
        x = 50,
        ycheck = 50,
        y = 50,
        xspeed = 0,
        yspeed = 0,
        power = 0.4,
        friction = 0.99,
        xwind = 0,
        ywind = 0,
        dead = true,
        timer = function(keys) {
            if (dead === true) {
                return;
            }
            if (keys[38] === true) {
                yspeed += power;
            }
            if (keys[40] === true) {
                yspeed -= power;
            }
            if (keys[37] === true) {
                xspeed += power;
            }
            if (keys[39] === true) {
                xspeed -= power;
            }
            xspeed = xspeed * friction - xwind;
            yspeed = yspeed * friction - ywind;
            if (Math.abs(xspeed) < 0.004) {
                xspeed = 0;
            }
            if (Math.abs(xspeed) < 0.004) {
                xspeed = 0;
            }
            x -= xspeed;
            y -= yspeed;
            plane.move(x,y);
        };
    return {
        init: function() {
            if (inited != true) {
                inited = true;
                el = document.getElementById('ball');
                roller.register(timer, 'time');
            }
        }
    };
}();

This all works, but the ball has no rolling animation! The image just slides to the left or right How can I add this? I found this tutorial: http://www.emanueleferonato.com/2007/06/10/creation-of-realistic-spheres-in-flash-with-textures-and-masking/ which I thought could help me out.

Unfortunately, this is for a flash ball (I was hoping this would apply in some sort to JS too). This tutorial shows exactly what I want: a ball with rolling animation (see the tutorial page near the end of the tutorial the ball with the leopard skin, just below: Lines 26-37: If the position of the texture relatively to the ball...).

How can I apply this to my JS ball? Any thoughts?

Kind regards and a happy new year

ps I use/load jquery as well

--EDIT--------

Created a fiddle: http://jsfiddle.net/mauricederegt/dhUw5/

1- open the fiddle

2- click the 1

3- use the arrow keys to move the ball around, stay on the green field!

4- see, no rolling effect

like image 619
Maurice Avatar asked Dec 29 '12 14:12

Maurice


People also ask

Can you make animations with JavaScript?

JavaScript animations are done by programming gradual changes in an element's style. The changes are called by a timer. When the timer interval is small, the animation looks continuous.

Can JavaScript develop some animation effects?

By using JavaScript animation libraries, you can program website elements to 'whoosh', 'fade', or 'bounce'. There are many types of JavaScript animations, like: Content boxes that slide in on page load. Hilarious text animations, and more.

How do you animate text in JavaScript?

To make an animation possible, the animated element must be animated relative to a "parent container". The container element should be created with style = "position: relative". The animation element should be created with style = "position: absolute".

How do animations work in JavaScript?

An animation can be implemented as a sequence of frames – usually small changes to HTML/CSS properties. For instance, changing style. left from 0px to 100px moves the element. And if we increase it in setInterval , changing by 2px with a tiny delay, like 50 times per second, then it looks smooth.


3 Answers

To have the same effect as in the Flash example you linked you just have to add a background to the element and move that accordingly.

I replaced your img element with a span and gave it the background-image via CSS and a border-radius to make it round. In your plane.move function I added the following line:

document.getElementById('ball').style.backgroundPosition = x + 'px ' + y +'px';

Voilá, same effect as in the Flash example: http://jsfiddle.net/dhUw5/1/

like image 51
dave Avatar answered Oct 06 '22 17:10

dave


You would probably use HTML5 canvas. You would clip part of the image used as the ball's surface using drawImage and then mask it to get a circle shape. Then you can animate it by redrawing the canvas, with the clipping position (sx, sy) altered in a similar way to the flash example you linked to. (Following is not tested; make a jsfiddle with your original code if you want to try it.)

// ... when the user moves
this.sy += yspeed;
this.sx += xspeed;
if (this.sx > textureSize) {
    this.sx -= textureSize;
}
else if (this.sx < 0) {
    this.sx += textureSize;
}
if (this.sy > textureSize) {
    this.sy -= textureSize;
}
else if (this.sy < 0) {
    this.sy += textureSize;
}

// ... redraw the ball once every frame
context.clearRect(0, 0, canvasWidth, canvasHeight); // clear the canvas
context.save();
context.beginPath();
context.arc(this.x, this.y, ballRadius, Math.PI * 2, false);
context.clip();    
context.drawImage(ballImage, this.sx, this.sy, 
                  ballDiameter, ballDiameter, 
                  this.x, this.y,
                  ballDiameter, ballDiameter);      // redraw the ball      
context.restore();

Alternatively you could use a div with the texture as a background image, and mask it to make a circle using CSS3 or by overlaying another image (see Best way to mask an image in HTML5). Then you would change the coordinates of the background image (texture) using

ballElement.style.backgroundPosition = this.sx + 'px ' + this.sy + 'px';

like image 22
Stuart Avatar answered Oct 06 '22 17:10

Stuart


This is quite easy if you use CSS transforms. In this example the speed of rotation is determined according to the scalar value of the speed the ball is currently traveling at:

    var increment = Math.round(Math.sqrt(Math.pow(xspeed, 2) + Math.pow(yspeed, 2)));
    if (!isNaN(increment)) {
        currangle = currangle + ((xspeed < 0 ? 1 : -1) * increment);
    }

    $('#ball').css({
        '-webkit-transform': 'rotate(' + currangle + 'deg)'
    });

    $('#ball').css({
        '-moz-transform': 'rotate(' + currangle + 'deg)'
    });

This code goes in the move method in plane. Here is a demonstration: http://jsfiddle.net/BahnU/show/

like image 1
Asad Saeeduddin Avatar answered Oct 06 '22 15:10

Asad Saeeduddin