I created a sprite which moves in a circular motion. I want to change the direction if the mouse button (touch) is clicked, but when the mouse is clicked, the direction does not change.
This is my code:
create: function() {
this.stage.backgroundColor = '#FFFFFF';
x = this.world.centerX;
y = this.world.centerY;
this.direction = 1;
this.speedDelta = 0.002;
this.radius = 114;
this.physics.startSystem(Phaser.Physics.ARCADE);
//adding player
this.player = this.add.sprite(x, y, 'player');
this.player.anchor.setTo(0.5, 0.5);
this.game.physics.arcade.enable(this.player);
this.input.onDown.add(this.changeDirection, this);
},
update: function() {
if (this.direction == 1) {
this.speedDelta = 0.002;
} else if (this.direction == 1) {
this.speedDelta = -0.002;
}
var period = this.time.now * this.speedDelta;
this.player.x = Math.cos(period) * this.radius;
this.player.y = d + Math.sin(period) * this.radius;
},
changeDirection: function() {
this.direction = -this.direction;
}
}
Your basic assumptions about the behavior of cos and sin are incorrect. You can't simply change the sign of the input and get a different answer.
Notice:
cos(pi/4) = 0.707
cos(-pi/4) = 0.707
sin(pi/4) = -0.707
sin(-pi/4) = -0.707
Also I think your code would benefit by using a slightly different approach in general.
Currently you're recalculating the position from scratch on every update cycle. To get the behavior you want, I think it would be simpler to instead calculate a location delta based off of the speed and direction, then simply add the delta to the current location.
That would also allow you to eliminate your conditional statement, which will make the code cleaner.
I have been working on a JS project where a sun goes around an image in a circle, and based on its position a higher index div will change opacity to make it darker or lighter. My problem is; while at one point the Sun moved in a circle, it no longer does. I have tried many things to fix this, but to no avail. My documented code is as follows:
<style>
sun{
position: absolute;
z-index: 1;
}
dark-light{
z-index: 2;
}
</style>
CSS:^ JS:v
<script>
move();
//calls move
function move(){
//set rot
var rot = 180;
var pictureToDisplay = prompt('Please insert link to picture to display','URL Necessary to function properly, but not required. Press enter to continue.');
//asks user to insert picture link for STATIONARY picture
var img = document.getElementById('img');
if (pictureToDisplay == 'URL Necessary to function properly, but not required. Press enter to continue.'){
}else{
img.src = pictureToDisplay;
}
//Sets stationary picture
window.setInterval( function() {
//Repeats every 75 milliseconds forever.
var obj = document.getElementById('sun');
// obj. is equal to id sun
var top = (Math.sin(rot)*500)+500;
var left = (Math.cos(rot)*500)+500;
//uses var rot, sine, and cosine to determine moving sun position
var toppx = top + 'px';
var leftpx = left + 'px';
//adds the px after those values
obj.style.top = toppx;
obj.style.left = leftpx;
//attempts to set position of obj (id sun)
var darkToLight = -0.5+(top/500);
//determines opacity of div using var top
//document.write(rot+' = rot : ');
var lightDiv = document.getElementById('dark-light');
// same as var obj, but with the div
lightDiv.style.opacity = darkToLight;
//sets lightDiv to opacity
//document.write(toppx,' ,',leftpx,' : ');
rot = (rot+0.01) % 360;
//moves rot up by 0.01, modulate 360
}, 75);
//back to top of setInterval
}
</script>
P.S. I know no JQuery.
Edit: The position of all is absolute, 0,0 is the top left corner of the page. I made sure not to deal with negatives. The sun should be absolute to the page, as its in nothing.
Ok, I figured out that I apparently am not too good with css, and after adding in style="position:absolute"; it now works fine.
I'm making a vertical scrolling platform game using Phaser, but I can't figure out how to create randomly placed platforms to jump on. This is the code I have so far (removed unneccesary stuff):
Platformer.Game = function (game) {
this._platforms = null;
this._platform = null;
this._numberOfPlatforms = 15;
this._x = this.x;
this._y = this.y;
};
Platformer.Game.prototype = {
create: function (){
this.physics.startSystem(Phaser.Physics.ARCADE);
this.physics.arcade.gravity.y = 200;
this._platforms = this.add.group();
Platformer.platform.createPlatform(this);
Platformer.platform.createPlatform(this);
Platformer.platform.createPlatform(this);
Platformer.platform.createPlatform(this);
Platformer.platform.createPlatform(this);
Platformer.platform.createPlatform(this);
game.camera.follow(this._player);
},
managePause: function () {
this.game.paused = true;
var pausedText = this.add.text(100, 250, "Game paused. Click anywhere to continue.", this._fontStyle);
this.input.onDown.add(function(){
pausedText.destroy();
this.game.paused = false;
}, this);
},
update: function () {
}
};
Platformer.platform = {
createPlatform: function (game) {
var posX = Math.floor(Math.random() * Platformer.GAME_WIDTH * this._numberOfPlatforms * 70);
var posY = Math.floor(Math.random() * Platformer.GAME_HEIGHT * this._numberOfPlatforms * 50);
var platform = game.add.sprite(posX, posY, 'platform');
game._platforms.add(platform);
platform.events.onOutOfBounds.add(this.removePlatform, this);
},
removePlatform: function (game) {
this._platform.kill();
}
}
I can get it to work to place them randomly, but the idea of a platformer should be you could actually jump on it. With enough distance but not too much, so I guess not entirely random.
Hope you have some ideas!
Here's a simple approach, just a start really.
The idea is to build up some basic rules basing the position of each platform on the one that came before. For example, if the last one was on the left, put the next one somewhere to the right.
Min/max ranges are also good in these situations: In this example the next platform is always at least 200px higher up than the last and no more than 300px higher.
There's a playable example here on codepen
platforms = game.add.group();
platforms.enableBody = true;
platforms.physicsBodyType = Phaser.Physics.ARCADE;
// start off on the left 220px above the ground
var x = 0, y = height - 220;
// keep adding platforms until close to the top
while(y > 200) {
var platform = platforms.create(x, y, 'platform');
platform.body.immovable = true;
platform.body.allowGravity = false;
// find center of game canvas
var center = width / 2;
if(x > center) {
// if the last platform was to the right of the
// center, put the next one on the left
x = Math.random() * center;
}
else {
// if it was on the left, put the next one on the right
x = center + Math.random() * (center - platformWidth);
}
// place the next platform at least 200px higher and at most 300px higher
y = y - 200 - 100 * Math.random();
}
I have an image of a ball, a cup, and an inner and outer div that represent a throw power bar.
When the user clicks the ball, the power bar starts to increment and then decrements. When the user clicks the ball a 2nd time, the throw power bar stops and the ball is thrown.
As I have began coding this, I realized certain things are going to be extremely complicated, even though the idea itself is rather simple.
For example, I want the ball to be able to "bounce", meaning I will need to not only keep track of the balls x and y coordinates, but also a z coordinate representing depth.
When the ball falls to bounce, the z coordinate with be decremented, and the image of the ball should be scaled down in size, and when it begins bouncing back up, it should scale up in size, again based on the z coordinate. I also want the ball to bounce off the cup if the z coordinate is below a certain value by the time it reaches the cup, go into the cup if it is a certain sweet spot, or go over the cup if it's z value is over that sweet spot.
In the interest of keeping this somewhere short, I'll just post what I have so far. This example is lacking certain things that I was hoping people here could help me with.
http://jsfiddle.net/7Lsh78nw/
<html>
<head>
<style>
#ball {
position:absolute;
width:75px;
height:75px;
}
#cup1 {
position:absolute;
left:375px;
}
#outerPowerMeter {
position:absolute;
width:25px;
height:100px;
background-color:red;
}
#innerPowerMeter {
position:absolute;
width:25px;
height:100px;
background-color:black;
}
</style>
<script>
window.onload = function() {
var ball = document.getElementById("ball");
var yPos = 500;
var xPos = 400;
var zPos = 100;
var ballWidth = 75;
var ballHeight = 75;
var throwBallInterval;
var changeBallSizeInterval;
ball.style.top = yPos + "px";
ball.style.left = xPos + "px";
var cup1 = document.getElementById("cup1");
var powerMeter = document.getElementById("innerPowerMeter");
var powerMeterValue = 0;
var powerMeterHeight = 100;
var powerMeterActive = false;
var powerMeterInterval;
powerMeter.style.height = powerMeterHeight + "px";
ball.onclick = function() {
if (powerMeterActive == false) {
powerMeterActive = true;
startPowerMeter();
} else {
powerMeterActive = false;
stopPowerMeter();
throwBall();
}
}
function throwBall() {
throwBallInterval = setInterval(function() {
yPos = yPos - 1;
ball.style.top = yPos + "px";
}, 1);
changeBallSizeInterval = setInterval(function() {
zPos = zPos - 1;
ballWidth = ballWidth - 1;
ballHeight = ballHeight - 1;
ball.style.width = ballWidth;
ball.style.height = ballHeight;
}, 100);
}
function startPowerMeter() {
var increment = true;
powerMeterInterval = setInterval(function() {
if (increment == true) {
powerMeterValue = powerMeterValue + 1;
powerMeter.style.height = (powerMeterHeight - powerMeterValue) + "px";
if (powerMeterValue == 100) {
increment = false;
}
} else {
powerMeterValue = powerMeterValue - 1;
powerMeter.style.height = (powerMeterHeight - powerMeterValue) + "px";
if (powerMeterValue == 0) {
increment = true;
}
}
},1);
}
function stopPowerMeter() {
clearInterval(powerMeterInterval);
}
function detectCollision() { }
function detectGoal() { }
}
</script>
</head>
<body>
<img id="cup1" src="http://beerwar.com/game/images/cup.png">
<img id="ball" src="http://beerwar.com/game/images/ball.png">
<div id="outerPowerMeter">
<div id="innerPowerMeter"></div>
</div>
</body>
</html>
Since you posted such a detailed case, i thought i give you some pointers. Mind you: this is mostly vector math. I'm not a physicist either, but vector math isn't that complicated luckily! Some pythagoras here and there and you are set.
A good an fast library for that is glMatrix
A couple of things to get you going. Please note: it is pseudo code, but it does explain the concept of it.
Keep a vector for the position of the ball
Keep a vector for the position of the cup (where the ball should hit)
Keep a vector for the position of 'the camera' (since you want to scale the ball based on distance from the camera. Doesn't have to be accurate, just get the idea across)
Keep a vector for the 'direction of the force' you are going to apply to the ball. (this can be multiplied with the force from your force meter)
Keep a vector for the 'velocity of the ball'
Keep a vector for the 'gravity'
Your 'throw' function would become something along the lines of:
ball.velocity = throw.direction * throw.power
setInterval(tick,50);
Basicly, your 'tick' function (the function you apply every x-time)
ball.velocity += gravity; // we apply gravity to the speed of the ball. Pulling it down
ball.position = ball.position + ball.velocity // we add the velocity to the position every tick
if (ball.position.y < ball.radius) // if the ball is below its radius, it is colliding with the ground
{
ball.position.y = 0 - ball.position.y; // just invert its 'up' position, to make it not collide with the ground anymore
// to make the ball go back up again, invert its 'up' velocity. Gravity will get it down eventually
// dampening applied so it will bounce up less every time. For instance make that 0.9.
ball.velocity.y = 0 - (ball.velocity.y * dampening);
}
// the scale of the ball is not determined by its height, but by its distance from the camera
distanceFromCamera = (camera.position - ball.position).length()
ball.scale = 100 - (distanceFromCamera / scaleFactor);
// to make a simply guess if we are hitting the target, just check the distance to it.
distanceFromTarget = (cup.target.position - ball.position).length()
if (distanceFromTarget <= cup.target.radius) // if we 'hit the target'
handleHit()
How do I run a sprite animation when pressing the left or right arrow keys in JavaScript? Here's my code:
var avatarX = 0;
var avatarY = 240;
var avatarImage;
var counter = 1;
var XWIDTH = 0;
var WIDTH = 400;
var dx = 5;
var tt;
var gameCanvas;
var context;
var moving;
var animationCounter = 1;
window.addEventListener('keydown', KeyDown);
function setUpGame() { //This is the function that is called from the html document.
gameCanvas = document.getElementById("gameCanvas"); //Declare a new variable & assigns it the id of the CANVAS from the html document.
context=gameCanvas.getContext("2d");
context.font = "18px Iceland";
context.textBaseline = "top";
avatarImage = new Image(); //Declaring a new variable. This is so that we can store the image at a later date.
avatarImage.onload=function(){
// avatarImage is now fully loaded and ready to drawImage
context.drawImage(avatarImage, Math.random() * 100, avatarY);
// start the timer
tt = setInterval(function(){counTer()},1000);
setInterval(handleTick, 25);
}
avatarImage.addEventListener('load', startLoop, false);
avatarImage.src = "img/ships.png"; //Ditto from above.
}
function startLoop() {
console.log("Detecting whether moving to the right is: " + moving);
if(moving == 0) {
gameLoop();
}
}
function gameLoop() {
setTimeout(gameLoop, 100);
handleTick();
}
function KeyDown(evt) {
switch (evt.keyCode) {
case 39: /*Arrow to the right*/
if(avatarX + dx <WIDTH && avatarX + dx >XWIDTH) {
avatarX += dx;
moving = 0;
}
break;
case 37: /*Arrow to the left*/
if(avatarX - dx >XWIDTH) {
avatarX -= dx;
moving = 1;
}
break;
}
}
function counTer() {
if(counter == 60) {
clearInterval(tt);
} else {
counter++;
}
}
function handleTick() {
context.clearRect(0,0,gameCanvas.width,gameCanvas.height);
context.drawImage(avatarImage, 32*animationCounter, 0, 32,32, avatarX, avatarY, 64, 64);
context.fillText("Seconds: " + counter, 5, 5);
context.fillText("1 is Right, 2 is Left, 0 is idle: " + moving, 20, 20);
animationCounter++
if(animationCounter >1) {
animationCounter = 0;
}
}
There are many ways to implement animation. The one i use is pretty easy and looks something like this:
var player = {
x: 0,
y: 0,
width: 50,
height: 100,
sprite: {
column: 0,
row: 0,
height: 50,
width: 100
},
image: PlayerImage,
animation: {
active: true, //Determines if the animation is running or not.
counter: 0,
progress: 0,
sequence: []
}
}
//This functions fires when the left arrow is pressed.
var onLeft = function(){
player.animation.sequence = [{column: 0, row: 0, t: 12}, {column: 1, row: 0, t: 12}, {column: 2, row: 0, t: 12}];
player.animation.active = true;
}
//This functions fires when the right arrow is pressed.
var onRight = function(){
player.animation.sequence = [{column: 0, row: 1, t: 12}, {column: 1, row: 1, t: 12}, {column: 2, row: 1, t: 12}];
player.animation.active = true;
}
//This function fires when no arrow are pressed.
var standingStill = function(){
player.animation.active = false;
}
var handleTick = function(){
//Clear the canvas.
context.canvas.width = context.canvas.width;
//If the animation is active.
if(player.animation.active){
//If the counter >= tick in the sequence. If not, just keep on increasing the counter value.
if(player.animation.counter >= player.animation.sequence[player.animation.progress]){
player.animation.counter = 1;
if(player.animation.progress >= player.animation.sequence.length - 1){
player.animation.progress = 0;
}else{
player.animation.progress++;
}
var currentFrame = player.animation.sequence[player.animation.progress];
//Change player.sprite column and row.(new frame)
player.sprite.column = currentFrame.column;
player.sprite.row = currentFrame.row;
}else{
player.animation.counter++;
}
}
context.drawImage(player.image, player.sprite.column * player.sprite.width, player.sprite.row * player.sprite.height, player.sprite.width, player.sprite.height, player.x, player.y, player.width, player.height)
}
The sequence is an array that contains objects that look like that: {column: 0, row: 0, t: 12} Every object is a frame. The column value is the current x of the sprite, the row is the y of the sprite. The script automatically creates the x and the y value, so all you need to add is value like 0, 1, 3, 5, and so on.(Just which frame it is on either x or y axis.) So for example, if the column is 0 and the row is 0, this is the frame that is in the top-left corner(the first frame). The t value stands for tick, this determines how many ticks there has to happend before the animation goes to the next frame.
Player.sprite also has properties width and height, that's the width and the height of the frame, it is often the same value as the width and height of the player object.
You have to make your own player.animation.sequence in onLeft and onRight function so it animates how you want it to animate.
I hope you understood what i meant. This might seem complicated, but it really isn't and if you don't get it now, don't worry, you'll get it eventually. If you really have difficulties with understanding, just ask.
Edit: First of all i highly recommend using objects to store information about entities. It makes game making much easier and cleaner. Just look at the player object, it's much easier to get the x simply by writing player.x than PlayerX. It looks more professional too. :) And when you have to give a lot of information about your entity you don't have to pass many arguments, you pass the whole object. Example:
//Entity properties stored in separate variable.
function animate(EntityX, EntityY, EntitySpriteX, EntitySpriteY, ...){
var x = EntityX;
//And so on...
}
//Entity stored in an object.
function animate(Entity){
var x = Entity.x;
//And so on...
}
Anyway, back to your question. First, we have to add variables that store information about our sprite.
var avatarSpriteColumn = 0; //Sprite frame on the x axis.
var avatarSpriteRow = 0; //Sprite frame on the y axis.
var avatarSpriteWidth = 50; //The width of a frame.
var avatarSpriteHeight = 100; //The height of a frame.
We also have to add variables that store the information about the animation.
var animationActive = false; //A variable that controls if the animation is 'running'.
var animationCounter = 0; //How many frames(ticks) have passed since the last frame(animation frame) has changed. (I'm not good at describing variables. :P)
var animationProgress = 0; //Current animation frame.
var animationSequence = []; //Array that stores the sequence of animation, as i explained.
Then, in your handleTick function you have to add a code that will animate the sprite. You have to add this code before you draw your entity.
//If the animation is active.
if(animationActive){
//If the counter >= tick in the sequence. If not, just keep on increasing the counter value.
if(animationCounter >= animationSequence[animationProgress]){
animationCounter = 1;
//Reset the progress, so that next time another animation frame shows up.
if(animationProgress >= animationSequence.length - 1){
animationProgress = 0;
}else{
animationProgress++;
}
//Select information about the current animation frame and store it in a variable so it is easier to access.
var currentFrame = animationSequence[animationProgress];
//Change player.sprite column and row.(new frame);
avatarSpriteColumn = currentFrame.column;
avatarSpriteRow = currentFrame.row;
}else{
animationCounter.counter++;
}
}
Ok, now you have a code that animates the sprite, but how do we run it? Well, i see you have a variable called moving. It tells us in what direction the player is moving and if it is moving at all. It looks like you implemented it a little bit wrong. Right now your function that operates the keys looks like this:
function KeyDown(evt) {
switch (evt.keyCode) {
case 39: /*Arrow to the right*/
if(avatarX + dx <WIDTH && avatarX + dx >XWIDTH) {
avatarX += dx;
moving = 0;
}
break;
case 37: /*Arrow to the left*/
if(avatarX - dx >XWIDTH) {
avatarX -= dx;
moving = 1;
}
break;
}
}
The variable is supposed to return 1 if the entity is going to the right, 2 if it is going to the left and 0 if the entity is standing still, right? Right now it shows 0 when the entity is moving to the right and 1 when it is moving to the left. It also doesn't show us if the entity is idle. We have to fix it. Change it to something like this:
function KeyDown(evt) {
switch (evt.keyCode) {
case 39: /*Arrow to the right*/
if(avatarX + dx <WIDTH && avatarX + dx >XWIDTH) {
avatarX += dx;
moving = 1;
}
break;
case 37: /*Arrow to the left*/
if(avatarX - dx >XWIDTH) {
avatarX -= dx;
moving = 2;
}
break;
default:
moving = 0;
}
}
Ok, now we have to add this code to the handleTick function. This code starts the animation and changes the sequence.:
if(moving == 1){ //Moving in the right direction.
animationSequence = []; //Animation of moving in the right direction. Change the sequence to your own.
animationActive = true; //Run the animation.
}else if(moving == 2){ //Moving to the left.
animationSequence = []; //Animation of moving to the left. Change the sequence to your own.
animationActive = true; //Run the animation.
}else{
animationActive = false; //Stops the animation, but the last frame stays.
/*
Alternatively, if you want a separate frame or animation that is animating when the entity is standing, you run this code.
animationSequence = []; // Your sequence. If you want a single frame, with no animation just add one frame to the sequence.
animationActive = true;
*/
}
Now, the last thing we have to do is to draw the entity. In your case, this will look something like this:
context.drawImage(avatarImage, avatarSpriteColumn * avatarSpriteWidth, avatarSpriteRow * avatarSpriteHeight, avatarWidth, avatarHeight, avatarX, avatarY, 64, 64);
In the end your whole code will look something like this:
var avatarX = 0;
var avatarY = 240;
var avatarImage;
var counter = 1;
var XWIDTH = 0;
var WIDTH = 400;
var dx = 5;
var tt;
var gameCanvas;
var context;
var moving;
var animationCounter = 1;
var avatarSpriteColumn = 0; //Sprite frame on the x axis.
var avatarSpriteRow = 0; //Sprite frame on the y axis.
var avatarSpriteWidth = 50; //The width of a frame.
var avatarSpriteHeight = 100; //The height of a frame.
var animationActive = false; //A variable that controls if the animation is 'running'.
var animationCounter = 0; //How many frames(ticks) have passed since the last frame(animation frame) has changed. (I'm not good at describing variables. :P)
var animationProgress = 0; //Current animation frame.
var animationSequence = []; //Array that stores the sequence of animation, as i explained.
window.addEventListener('keydown', KeyDown);
function setUpGame() { //This is the function that is called from the html document.
gameCanvas = document.getElementById("gameCanvas"); //Declare a new variable & assigns it the id of the CANVAS from the html document.
context=gameCanvas.getContext("2d");
context.font = "18px Iceland";
context.textBaseline = "top";
avatarImage = new Image(); //Declaring a new variable. This is so that we can store the image at a later date.
avatarImage.onload=function(){
// avatarImage is now fully loaded and ready to drawImage
context.drawImage(avatarImage, Math.random() * 100, avatarY);
// start the timer
tt = setInterval(function(){counTer()},1000);
setInterval(handleTick, 25);
}
avatarImage.addEventListener('load', startLoop, false);
avatarImage.src = "img/ships.png"; //Ditto from above.
}
function startLoop() {
console.log("Detecting whether moving to the right is: " + moving);
if(moving == 0) {
gameLoop();
}
}
function gameLoop() {
setTimeout(gameLoop, 100);
handleTick();
}
function KeyDown(evt) {
switch (evt.keyCode) {
case 39: /*Arrow to the right*/
if(avatarX + dx <WIDTH && avatarX + dx >XWIDTH) {
avatarX += dx;
moving = 1;
}
break;
case 37: /*Arrow to the left*/
if(avatarX - dx >XWIDTH) {
avatarX -= dx;
moving = 2;
}
break;
default:
moving = 0;
}
}
function counTer() {
if(counter == 60) {
clearInterval(tt);
} else {
counter++;
}
}
function handleTick() {
context.clearRect(0,0,gameCanvas.width,gameCanvas.height);
if(moving == 1){ //Moving in the right direction.
animationSequence = []; //Animation of moving in the right direction. Change the sequence to your own.
animationActive = true; //Run the animation.
}else if(moving == 2){ //Moving to the left.
animationSequence = []; //Animation of moving to the left. Change the sequence to your own.
animationActive = true; //Run the animation.
}else{
animationActive = false; //Stops the animation, but the last frame stays.
/*
Alternatively, if you want a separate frame or animation that is animating when the entity is standing, you run this code.
animationSequence = []; // Your sequence. If you want a single frame, with no animation just add one frame to the sequence.
animationActive = true;
*/
}
//If the animation is active.
if(animationActive){
//If the counter >= tick in the sequence. If not, just keep on increasing the counter value.
if(animationCounter >= animationSequence[animationProgress]){
animationCounter = 1;
//Reset the progress, so that next time another animation frame shows up.
if(animationProgress >= animationSequence.length - 1){
animationProgress = 0;
}else{
animationProgress++;
}
//Select information about the current animation frame and store it in a variable so it is easier to access.
var currentFrame = animationSequence[animationProgress];
//Change player.sprite column and row.(new frame);
avatarSpriteColumn = currentFrame.column;
avatarSpriteRow = currentFrame.row;
}else{
animationCounter.counter++;
}
}
context.drawImage(avatarImage, avatarSpriteColumn * avatarSpriteWidth, avatarSpriteRow * avatarSpriteHeight, avatarWidth, avatarHeight, avatarX, avatarY, 64, 64);
context.fillText("Seconds: " + counter, 5, 5);
context.fillText("1 is Right, 2 is Left, 0 is idle: " + moving, 20, 20);
}
The only thing you have to do right now is to make your own animationSequences and check if it works, let me know if you have any problems with that.
Of course, the code i am using is more complicated and has more "abilities" and is easier to use(the code behind is more complicated), but hopefully this will help you.
I must also apoligize for making this thing seem so complicated, when it's not. I am bad at explaining.