create account

Tank Fire Game Using HTML SVG (Part-3) by onepice

View this thread on: hive.blogpeakd.comecency.com
· @onepice ·
$26.27
Tank Fire Game Using HTML SVG (Part-3)
![Untitled-1.fw.png](https://cdn.steemitimages.com/DQmc4pjGzN6hQFF6kUZcnFoRoacNxtbzyScnPvbTVLbexxC/Untitled-1.fw.png)

# Repository

<a href="https://github.com/premasagar/pablo">PabloJs</a>

<a href="https://github.com/onepicesteem">My Github Profile</a>

<a href="https://github.com/onepicesteem/Tank-Fire-Game-Using-HTML-SVG-Part-3">Tank Fire Game Using HTML SVG (Part-3)</a>

# What Will I Learn?

- You will learn how to create a variable element array.
- You will learn `circle()` method in `PabloJs`.
- You will learn how to use `setInterval()` function in `Javascript`.
- You will learn `Math.random()` and `Math.floor()` methods in `Javascript`.
- You will learn `object` creation process.

# Requirements

<a href="https://github.com/Microsoft/vscode">Visual Studio Code in GitHub</a>

# Difficulty

- Basic

# Tutorial Contents

In my previous articles I gave the tank the power to move and shoot. The tank is able to move with the arrow keys of the keyboard and with the space key it can shoot according to direction.

In this article we can place the targets that the tank will hit.

I will use the `circle()` method in pablojs when I'm setting to targets.

I'll place more than one ball on the playing field, so I'll keep all the balls in an `array` and access all the balls with the `for` loop.

I will make the shapes of the balls different from each other and adjust their speed according to their shape. I place each ball inside an `object`.

I'll randomly set up the balls' locations and dimensions on the playing field. I will use the `Math.random()` function for this operation.

I will use the `setInterval()` method, because the balls will be in continuous motion.

At the end of this article, you will learn how to create objects that are independent from each other in game programming and how to move objects.

Let’s start.

For a better understanding of the article, I divide the article into three parts:

- Creating Balls
- Moving the Balls
- Set Limits For a Playground

### Creating Balls
I've mentioned that I will place the properties of the balls in one object.

This object will hold the properties of a single ball, and after creating a certain number of these objects and throwing them into the array, we will have more than one ball.

To create a ball, we need the `x` and `y` coordinates in the playing field and the `radius` of the circle.

We can find the speed by looking at the radius of the circle, but let us store the `speed` of the ball within our object for convenience.

I will make the ball move in a cross way so I have to keep the `direction` property within this object.

After creating our balls, if the tank's bullet hits the ball, we have to remove the ball from the playground. If we do not store the whole circle in a variable after creating the ball, we cannot delete it when the bullet is hit.

Let's create our balls in the light of this information.

First create the necessary variables to keep the properties of the ball.
```
//Ball's features
var ballX;
var ballY;
var ballR;
var ballSpeed;
var ballDirection;
var ballObj;
```
<br>
I need to keep the number of balls on the screen in a variable. I will initially draw `4 balls` in order to be better understood.
```
//Number of balls
var ballNumber=4;
var ballArray=new Array();
```
<br>
With the `new Array()` method we can create a variable array of elements.

With pablojs we use the `circle()` method to create a circle for the screen. I'm using multiple circle () methods to create one function.
```
function ballBuilder(x,y,r){
  return svg.circle({
   cx: x,
   cy: y,
   r: r,
   fill:  '#5758BB'
  });
}
```
<br>
With the `ballBuilder()` function we can draw a known circle of `x` and `y` center points and `radius`.
Now I can draw the ball as number of `ballNumber`.

I have to create x and y points randomly so that the ball can be formed at any point.

I need to set the random function according to the size of the screen. When setting for point y, I should take between `0 and 700` points and when setting to the x point between `0 and 1100` points.

Of course, because these points are central points, it would make more sense to determine the points of the ball in the playground.
```
ballX=Math.floor(Math.random() * 1060) + 20;//Generate random numbers from 20 to 1080
ballY=Math.floor(Math.random() * 660) + 20;//Generate random numbers from 20 to 680
```
<br>
The radius and speed of the ball will be linked together. The bigger the ball, the slower the speed.

I'll set the radius of the largest ball to 20, and I'll find the speed of 20 by subtracting the radius of the ball.
```
  ballR=Math.floor(Math.random() * 10) + 10;//Generate random numbers from 10 to 20
  ballSpeed=20-ballR;
```
<br>
We need direction information of the ball. Once you've created it with direction information, we can figure out where to go.

I will set 4 places for directions.

The following illustration shows the direction of the ball.

#### Screenshot 1
 ![Untitled-1.fw.png](https://cdn.steemitimages.com/DQmZs5HeKXHVMB4Ev75VhjqZozL4yteBvic1yupLjKkriY9/Untitled-1.fw.png)
<br>
Then I can determine the direction of the ball with a number between 1 and 4.
```
ballDirection=Math.floor(Math.random() * 4) + 1;
```
<br>
Let's create these operations for all balls and add the object with the array `push()` method.
```
//for cycle to create all balls
for (var i = 0; i < ballNumber; i++) {

  ballX=Math.floor(Math.random() * 1060) + 20;//Generate random numbers from 20 to 1080
  ballY=Math.floor(Math.random() * 660) + 20;//Generate random numbers from 20 to 680
  ballR=Math.floor(Math.random() * 10) + 10;//Generate random numbers from 10 to 20
  ballSpeed=20-ballR;
  ballDirection=Math.floor(Math.random() * 4) + 1;//Generate random numbers from 1 to 4
  ballObj=ballBuilder(ballX,ballY,ballR)

    var ballObject={
      ballX:ballX,
      ballY:ballY,
      ballR:ballR,
      ballSpeed:ballSpeed,
      ballDirection:ballDirection,
      ballObj:ballObj
    }

    ballArray.push(ballObject);
}
```
<br>
So we placed 4 balls on the playground.

#### Screenshot 2
![jquery1.JPG](https://cdn.steemitimages.com/DQmVVsZCUeynsjNTShib2DzdrYpBcn91n9Bk89JHnXGXY1g/jquery1.JPG)
<br>
When we refresh the page, the balls are re-created.

#### Screenshot 3
![jquery2.JPG](https://cdn.steemitimages.com/DQmazC9Vs9XVHEQWdTeE5914JNPmgfTPH3F9gDdmqFCCAQL/jquery2.JPG)
<br>
### Moving the Balls

To move the balls first we need to know the process is renewed periodically. We can use the `setInterval()` method for this periodic refresh.

Since we have more than one ball, we have to use the for loop, and our first task in the for loop will be to delete the balls at their current position.

Thus, when we draw the next movement, there will not be more than one drawing.

We can use the `ballObj` variable to delete balls. We can perform the deletion using the `remove()` method.
```
setInterval(function(){

  for (var i = 0; i < ballNumber; i++) {
      ballArray[i].ballObj.remove();
//set direction
    }
} , 100);
```
<br>
We can change the x and y coordinates of the ball according to the direction information.

If we make these changes according to the `ballSpeed` variable, we will determine their speed.

#### Screenshot 4
![Untitled-2.fw.png](https://cdn.steemitimages.com/DQmUgH8sV1WszNUoA1yrFWusGL6z6FgwoTSsVmBHucp4uCb/Untitled-2.fw.png)
<br>
Adjust the directions according to the picture above.
```
if(ballArray[i].ballDirection==1){

        ballArray[i].ballX=ballArray[i].ballX+ballArray[i].ballSpeed;
        ballArray[i].ballY=ballArray[i].ballY-ballArray[i].ballSpeed;

        ballArray[i].ballObj=ballBuilder(ballArray[i].ballX,ballArray[i].ballY,ballArray[i].ballR);

      }

      if(ballArray[i].ballDirection==2){

        ballArray[i].ballX=ballArray[i].ballX+ballArray[i].ballSpeed;
        ballArray[i].ballY=ballArray[i].ballY+ballArray[i].ballSpeed;

        ballArray[i].ballObj=ballBuilder(ballArray[i].ballX,ballArray[i].ballY,ballArray[i].ballR);

      }
      if(ballArray[i].ballDirection==3){

        ballArray[i].ballX=ballArray[i].ballX-ballArray[i].ballSpeed;
        ballArray[i].ballY=ballArray[i].ballY+ballArray[i].ballSpeed;

        ballArray[i].ballObj=ballBuilder(ballArray[i].ballX,ballArray[i].ballY,ballArray[i].ballR);

      }

      if(ballArray[i].ballDirection==4){

        ballArray[i].ballX=ballArray[i].ballX-ballArray[i].ballSpeed;
        ballArray[i].ballY=ballArray[i].ballY-ballArray[i].ballSpeed;

        ballArray[i].ballObj=ballBuilder(ballArray[i].ballX,ballArray[i].ballY,ballArray[i].ballR);

      }
```
<br>
I change the `ballX,  and `ballY` variables of the ball according to the `ballDirection` variable and redraw the ball.

#### Screenshot 5
![ezgif1.gif](https://cdn.steemitimages.com/DQmYoML2a9Fs1HMtKbV6z2vnUtsmK5ZmZs54r1G696icpD3/ezgif1.gif)
<br>
### Set Limits For a Playground

Our balls are moving but they disappear when they exceed the limits of the playing field.

To solve this problem, we must change the direction of the ball when the ball reaches the game limit.

We must direct the ball in the opposite direction to the direction it came from.

#### Screenshot 6
![Untitled-3.fw.png](https://cdn.steemitimages.com/DQmVbU63zDp5KLZjWrWkZf3xz12L5qdizmwy5r7qA5Pxb7D/Untitled-3.fw.png)
<br>
#### Screenshot 7
![Untitled-4.fw.png](https://cdn.steemitimages.com/DQmS4YLA13ssv5oU2jgucMx6rxu2fN2BHidJvenGqHML87R/Untitled-4.fw.png)
<br>
As shown in the picture above, the ball can come to the limits in two directions.

The vertical boundaries come from below and from the top and from the right and left to the horizontal boundaries.

In setInterval()
```
if (ballArray[i].ballY<10) {
          if(ballArray[i].ballDirection==1){
            ballArray[i].ballDirection=2;
          }
          if(ballArray[i].ballDirection==4){
            ballArray[i].ballDirection=3;
          }
      }

      if (ballArray[i].ballY>690) {
          if(ballArray[i].ballDirection==2){
            ballArray[i].ballDirection=1;
          }
          if(ballArray[i].ballDirection==3){
            ballArray[i].ballDirection=4;
          }
      }

      if (ballArray[i].ballX<10) {
          if(ballArray[i].ballDirection==4){
            ballArray[i].ballDirection=1;
          }
          if(ballArray[i].ballDirection==3){
            ballArray[i].ballDirection=2;
          }
      }
      if (ballArray[i].ballX>1080) {
          if(ballArray[i].ballDirection==1){
            ballArray[i].ballDirection=4;
          }
          if(ballArray[i].ballDirection==2){
            ballArray[i].ballDirection=3;
          }
      }
```
<br>
#### Screenshot 8
![ezgif2.gif](https://cdn.steemitimages.com/DQmeAuNdR1SVprMTeyT71c9A9nxXc3BQAAmBTbuSmDt21e6/ezgif2.gif)
<br>
Thus we have achieved the movement of the balls in different sizes and at different speeds.

# Curriculum

<a href="https://steemit.com/utopian-io/@onepice/tank-fire-game-using-html-svg-part-1">Tank Fire Game Using HTML SVG (Part-1)</a>

<a href="https://steemit.com/utopian-io/@onepice/tank-fire-game-using-html-svg-part-2">Tank Fire Game Using HTML SVG (Part-2)</a>

# Proof of Work Done

<a href="https://github.com/onepicesteem/Tank-Fire-Game-Using-HTML-SVG-Part-3">Tank Fire Game Using HTML SVG (Part-3)</a>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 74 others
properties (23)
authoronepice
permlinktank-fire-game-using-html-svg-part-3
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","jquery","pablojs","game-developer"],"image":["https://cdn.steemitimages.com/DQmc4pjGzN6hQFF6kUZcnFoRoacNxtbzyScnPvbTVLbexxC/Untitled-1.fw.png","https://cdn.steemitimages.com/DQmZs5HeKXHVMB4Ev75VhjqZozL4yteBvic1yupLjKkriY9/Untitled-1.fw.png","https://cdn.steemitimages.com/DQmVVsZCUeynsjNTShib2DzdrYpBcn91n9Bk89JHnXGXY1g/jquery1.JPG","https://cdn.steemitimages.com/DQmazC9Vs9XVHEQWdTeE5914JNPmgfTPH3F9gDdmqFCCAQL/jquery2.JPG","https://cdn.steemitimages.com/DQmUgH8sV1WszNUoA1yrFWusGL6z6FgwoTSsVmBHucp4uCb/Untitled-2.fw.png","https://cdn.steemitimages.com/DQmYoML2a9Fs1HMtKbV6z2vnUtsmK5ZmZs54r1G696icpD3/ezgif1.gif","https://cdn.steemitimages.com/DQmVbU63zDp5KLZjWrWkZf3xz12L5qdizmwy5r7qA5Pxb7D/Untitled-3.fw.png","https://cdn.steemitimages.com/DQmS4YLA13ssv5oU2jgucMx6rxu2fN2BHidJvenGqHML87R/Untitled-4.fw.png","https://cdn.steemitimages.com/DQmeAuNdR1SVprMTeyT71c9A9nxXc3BQAAmBTbuSmDt21e6/ezgif2.gif"],"links":["https://github.com/premasagar/pablo","https://github.com/onepicesteem","https://github.com/onepicesteem/Tank-Fire-Game-Using-HTML-SVG-Part-3","https://github.com/Microsoft/vscode","https://steemit.com/utopian-io/@onepice/tank-fire-game-using-html-svg-part-1","https://steemit.com/utopian-io/@onepice/tank-fire-game-using-html-svg-part-2"],"app":"steemit/0.1","format":"markdown"}
created2018-09-18 11:30:00
last_update2018-09-18 11:30:00
depth0
children4
last_payout2018-09-25 11:30:00
cashout_time1969-12-31 23:59:59
total_payout_value19.985 HBD
curator_payout_value6.281 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length11,266
author_reputation9,626,549,398,383
root_title"Tank Fire Game Using HTML SVG (Part-3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,575,357
net_rshares19,829,723,936,328
author_curate_reward""
vote details (138)
@steem-ua ·
#### Hi @onepice!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-tank-fire-game-using-html-svg-part-3-20180922t042551z
categoryutopian-io
json_metadata"{"app": "beem/0.19.54"}"
created2018-09-22 04:25:54
last_update2018-09-22 04:25:54
depth1
children0
last_payout2018-09-29 04:25:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length286
author_reputation23,214,230,978,060
root_title"Tank Fire Game Using HTML SVG (Part-3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,912,740
net_rshares0
@steemitboard ·
Congratulations @onepice! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

[![](https://steemitimages.com/70x80/http://steemitboard.com/notifications/posts.png)](http://steemitboard.com/@onepice) Award for the number of posts published

<sub>_Click on the badge to view your Board of Honor._</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



> Support [SteemitBoard's project](https://steemit.com/@steemitboard)! **[Vote for its witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1)** and **get one more award**!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-onepice-20180920t041138000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2018-09-20 04:11:36
last_update2018-09-20 04:11:36
depth1
children0
last_payout2018-09-27 04:11:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length680
author_reputation38,975,615,169,260
root_title"Tank Fire Game Using HTML SVG (Part-3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,731,301
net_rshares0
@utopian-io ·
Hey, @onepice!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-tank-fire-game-using-html-svg-part-3-20180924t000515z
categoryutopian-io
json_metadata"{"app": "beem/0.19.42"}"
created2018-09-24 00:05:15
last_update2018-09-24 00:05:15
depth1
children0
last_payout2018-10-01 00:05:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length589
author_reputation152,955,367,999,756
root_title"Tank Fire Game Using HTML SVG (Part-3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id72,076,803
net_rshares0
@yokunjon · (edited)
$0.05
I thank you for your contribution. Here is my thought;

* Titles show what your post is about, so use them wisely. When defining titles, choosing and positioning words is essential to gain the user's attention. Giving general words priority than the rest is the key to achieve that. So, consider putting "HTML-SVG-PabloJS" ahead of the title and explain what you are doing in this part, e.g., implementing moving targets.
----
Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/22211424).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
👍  , , , , , , ,
properties (23)
authoryokunjon
permlinkre-onepice-tank-fire-game-using-html-svg-part-3-20180922t035745368z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/22211424","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-09-22 03:57:45
last_update2018-09-22 03:58:57
depth1
children0
last_payout2018-09-29 03:57:45
cashout_time1969-12-31 23:59:59
total_payout_value0.046 HBD
curator_payout_value0.006 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length917
author_reputation19,266,807,595,513
root_title"Tank Fire Game Using HTML SVG (Part-3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id71,911,256
net_rshares46,968,369,804
author_curate_reward""
vote details (8)