Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / operating-systems / Windows / Win8

BreaknBounce

4.85/5 (8 votes)
4 Sep 2013CPOL14 min read 29K   1K  
Touch break and move the game objects

This article is an entry in our AppInnovation Contest. Articles in this sub-section are not required to be full articles so care should be taken when voting.

Introduction

  • Platform:Windows 8 Desktop
  • Category:-All-in-One  Games
  • Name:-BreaknBounce

Overview

The simple idea of the game is to touch the objects see it divide and break again.

Image 1

The game comprises of  objects in a space where we can interact with the objects. The game comprises of 3 playing objects and a static object plane. Now our concern would be to bring the objects at a place where we can see it or either take it away from the plane make it fall below. This game will support multitouch and can be easily installed in tablets as well as All-in-ones. The entire game will give users a very good experience of how touch works in the devices.   

The pictorial representation of how the game behaves with accelerometer inputs. 

Image 2

GAME OBJECTS 

  1. Sphere
  2. Cube
  3. Capsules
  4. The plane

In Figure

Image 3

Now the Catch 

The game brings game physics in action and will allow users to interact with it. The simple concept of objects being divided into Simpler objects of the same nature is in effect. Each Time you interact with the object a different color of object will be formed.

Key Inputs for interacting

This game is fully multitouch with accelerometer support as of now and realize the game potential by playing the demo given. How the game will be compiled

Image 4

Work in progress:- 

1)NFC to connect and play between two devices

Need ways to find out how we can attach the Windows.Networking.Proximity dll files to attach to Unity.A GUI button to interact with other devices 

As NFC is not supported in Lenovo AIO i am dropping this idea

2)A Gui Interface screen to close the application.

3)A Webcam integration for the gameobjects to make it more enjoyable.

4)Integration of Gyroscope with the app already tested i will implement it at later stages..

5)Integration of Intel Perceptual SDK with additional scenes attached to game so that with the GUI button you can switch over to Use The game mechanics for Intel Perceptual SDK..

As of now Download the exe touch,tap tilt to feel it.Tested with Ultrabook.Accelerometer sensors works best when the balls or sphere objects are broken into smaller or the tiniest part .See the balls jump move out of vicinity back in action with screen movements.

Game ScreenShots:- 

Image 5

Initial project files in Unity

Image 6

ScreenShot 1 from the game

Image 7

ScreenShot 2Image 8

Screenshot3

Image 9

Background

I had always felt that people like to touch the objects and see them in action with different colors.It brings a joy to their face and this is the idea to work with.

Using the code

I am giving a brief input on the code of the Cube that was implemented with Unity.This code is used to get the breaking or dividing effect of game object.

Breaker.cs

C#
//
// using UnityEngine;
using TouchScript.Gestures;

public class Breaker : MonoBehaviour
{
    public Transform CubePrefab;
    public float Power = 10.0f;

    private Vector3[] directions = {
                                       new Vector3(1, -1, 1),
                                       new Vector3(-1, -1, 1),
                                       new Vector3(-1, -1, -1),
                                       new Vector3(1, -1, -1),
                                       new Vector3(1, 1, 1),
                                       new Vector3(-1, 1, 1),
                                       new Vector3(-1, 1, -1),
                                       new Vector3(1, 1, -1)
                                   };

    private void Start()
    {
        GetComponent<tapgesture>().StateChanged += HandleStateChanged;
    }

    private void HandleStateChanged(object sender, TouchScript.Events.GestureStateChangeEventArgs e)
    {
        if (e.State == Gesture.GestureState.Recognized)
        {
            if (transform.localScale.x > 0.05f)
            {
                Color color = new Color(Random.value, Random.value, Random.value);
                for (int i = 0; i < 8; i++)
                {
                    var c = Instantiate(CubePrefab) as Transform;
                    c.parent = transform.parent;
                    c.name = "Cube";
                    c.localScale = 0.5f*transform.localScale;
                    c.position = transform.TransformPoint(c.localScale.x/10.0f*directions[i]);
                    c.rigidbody.velocity = Power*Random.insideUnitSphere;
                    c.renderer.material.color = color;
                }
            }
            Destroy(gameObject);
        }
    }
}

//

I am mixing for the first time coding Languages C# as well JavaScript.

This code shows how the accelerometer inputs have been handled

Accel.js

JavaScript
//
#pragma strict
var speed = 10.0;

function Start () {

}

function Update () {
var dir : Vector3 = Vector3.zero;
 
// we assume that device is held parallel to the ground
// and Home button is in the right hand
 
// remap device acceleration axis to game coordinates:
// 1) XY plane of the device is mapped onto XZ plane
// 2) rotated 90 degrees around Y axis
dir.x = -Input.acceleration.y;
dir.z = Input.acceleration.x;
 
// clamp acceleration vector to unit sphere
if (dir.sqrMagnitude > 1)
dir.Normalize();
 
// Make it move 10 meters per second instead of 10 meters per frame...
dir *= Time.deltaTime;
 
// Move object
transform.Translate (dir * speed);

}

The script for spawning of objects

spawner.cs

C#
//
using TouchScript.Gestures;
using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour
{
    public Transform CubePrefab;
    public Transform Container;
    public float Scale = .5f;

    private void Start()
    {
        GetComponent<tapgesture>().StateChanged += HandleStateChanged;
    }

    private void HandleStateChanged(object sender, 
             TouchScript.Events.GestureStateChangeEventArgs e)
    {
        if (e.State == Gesture.GestureState.Recognized)
        {
            var gesture = sender as TapGesture;
            RaycastHit hit;
            gesture.GetTargetHitResult(out hit);

            Color color = new Color(Random.value, Random.value, Random.value);
            var c = Instantiate(CubePrefab) as Transform;
            c.parent = Container;
            c.name = "Cube";
            c.localScale = Vector3.one*Scale*c.localScale.x;
            c.position = hit.point + hit.normal * 2;
            c.renderer.material.color = color;

        }
    }
}

Extending my project

I am constantly working on upgrading my project and there is fun while I experiment and get the result. This updated article is another attempt to showcase how the game is evolving as i am working on it. More to follow. Let's begin..

Possible EDICE Integration:- 

What is an E-Dice?

It's a Virtual Dice that can be used in an app that you physically do it will give the same effect as you roll the normal dice.

Why useful?

The   Dice roll can be easily recognized by the app so you can use it your own effect.

How Can I use it in my Game?

Playing  with Numbers:-

The Logic of using the E-Dice

As each roll presents a number you can just use it to shift between Game Levels

Possible uses:-

  1.  When a roll of a E-Dice shows a Number 2  you can add an event listener to this app which you can use to change levels in a Game.
  2. Now you can add a game logic in a certain level where the object will act simultaneously with E-Dice and produce the same effect in the game such that the number 3 in Dice results in breaking the object into 3 pieces and henceforth.
  3. We can also use it to shift camera focus in a game as You see in the Level the Light Bolt as the balls fall down you can change the camera focus close to the ground with a roll of an E-Dice
  4. I can also add a logic where with a number appearing in the Dice breaks the game object to that many pieces as the number representing the Cube.

The Number 2 in dice splitting the Game object  to two  pieces 

The Figure shows how it works

Image 10  The game Logic extended to vectors. The sample code snippet shows how we can do a breaking effect to split 

it in two pieces.

The Number 2 in dice splitting the Game object to pieces

C#
//
//private Vector3[] directions = {
                                       new Vector3(1, -1, 1),
                                       new Vector3(-1, -1, 1),
                                                         };
//

The Number 4 in E-Dice splitting the game object to 4 pieces

C#
//
//    private Vector3[] directions = {
                                       new Vector3(1, -1, 1),
                                       new Vector3(-1, -1, 1),
                                         new Vector3(1, -1, 1),
                                       new Vector3(-1, -1, 1),
                                                                 };

Experimenting With the current project

I am adding a little up to changes to the game to utilize the Graphics available in Lenovo to

give a good viewing experience.I am extending Seth Gibson's Flocking  Unity model and adding

a  Touch Sensor and also Lighting effect to the balls connected by the source.

What is Flocking behaviour?

Flocking behavior is the behavior exhibited when a group of birds, called a flock, are foraging or in flight. There are parallels with the shoaling behavior of fish, the swarming behavior of insects, and herd behavior of land animals.

Image 11

 

Computer Science Simulations:-

Computer simulations and mathematical models which have been developed to emulate the flocking behaviors of birds can generally be applied also to the "flocking" behavior of other species. As a result, the term "flocking" is sometimes applied, in computer science, to species other than birds

How is the Simulation brought into Life in Unity Game

This simulation involves an AI logic simulation  to keep the objects  binded.It involves

Separation:-  steer to avoid crowding local flockmates

Alignment:-Steer Towards the  Local flockmates

Cohesion:- steer to move toward the average position (center of mass) of local flockmates

Image 12

I have extended the example with obstacles which create a lightning effect and are connected to center.You can touch these objects or obstacles and change the orientation.

Image 13

The Script for Obstacle:-

C#
//
//using UnityEngine;
using System.Collections;

public class LightningBolt : MonoBehaviour
{
    public Transform target;
    public int zigs = 100;
    public float speed = 1f;
    public float scale = 1f;
    public Light startLight;
    public Light endLight;
    
    Perlin noise;
    float oneOverZigs;
    
    private Particle[] particles;
    
    void Start()
    {
        oneOverZigs = 1f / (float)zigs;
        particleEmitter.emit = false;

        particleEmitter.Emit(zigs);
        particles = particleEmitter.particles;
    }
    
    void Update ()
    {
        if (noise == null)
            noise = new Perlin();
            
        float timex = Time.time * speed * 0.1365143f;
        float timey = Time.time * speed * 1.21688f;
        float timez = Time.time * speed * 2.5564f;
        
        for (int i=0; i < particles.Length; i++)
        {
            Vector3 position = Vector3.Lerp(transform.position, target.position, oneOverZigs * (float)i);
            Vector3 offset = new Vector3(noise.Noise(timex + position.x, timex + position.y, timex + position.z),
                noise.Noise(timey + position.x, timey + position.y, timey + position.z),
                noise.Noise(timez + position.x, timez + position.y, timez + position.z));
            position += (offset * scale * ((float)i * oneOverZigs));
            
            particles[i].position = position;
            particles[i].color = Color.white;
            particles[i].energy = 1f;
        }
        
        particleEmitter.particles = particles;
        
        if (particleEmitter.particleCount >= 2)
        {
            if (startLight)
                startLight.transform.position = particles[0].position;
            if (endLight)
                endLight.transform.position = particles[particles.Length - 1].position;
        }
    }    
}
//

More screenshots from the game:-

Image 14

The next figure shows the exit button in the game as well as well as  TouchPoint Objects

Image 15

Working on another Flocking Scenario(Work on Progress)  shown in next figureImage 16

VIDEO LINK FOR THIS LEVEL DEMO

The video link shows the game demo in Ultrabook and how the GUI will give a better look and feel and

good viewing experience in the  Lenovo AIO

FLOCKING DEMO

Features i will like to add to this Level

Accelerometer Support as well as the Breaking effect still in progress..

Games that used Flocking

HALF LIFE

for the flying bird-like creatures seen at the end of the game 

Image 17

In movies

Batman Returns

with computer generated bat swarms and armies of penguins marching through the streets of Gotham City

Image 18  

LIGHTNING BOLT LEVEL

Here you find the Game objects are attached to  a target by a lightning like effect when you touch them they break again and fall Down to ground .Here I would be using The accelerometer sensor to interact with the fallen object and there will be a scope for E-Dice with a roll the view shifts to secondary camera attached to plane(I have to get the SDK for E-Dice from Lenovo  to get it going).

The whole experience will be a new one and presented to end user in an innovative manner.

The figure shows the current status

Image 19

The next figure shows the game in action 

Image 20

Another figure showing the breaking effect with the objects

Image 21

VIDEO LINK FOR THIS LEVEL 

LIGHTNING EFFECT

The demo is shown on an Ultrabook and hence will Improve the overall experience of the Lenovo AIO

Things i am considering now

Making it compatible for 2 players.

The little knowledge that i have I was able to achieve this much as I learn more there will be more updates..

I HAVE INCLUDED ANOTHER DEMO OF THE GAME..

Using Smartphone to control the game 

I will be  creating web version of the game so that you will be able to play it at AIO with your

Smartphone (Android or IOS Device) works as Game Controller for you.

How it will Work?

It will work by having the device and the AIO in the same Network(Same Subnet).

Imagine controlling the balls from the mobile it is possible .It is possible using the

BrassMonkey SDK for Unity. Just download the app  from the Google Play Store or

Apple Store and you are good to go.

Conditions required to work with the AIO and the app

i) Ensure both the device and the host computer are on the same subnet. Since

Brass Monkey works on the local network, both the iPhone,Android and host computer must be connected to the same network. This does *not* mean that the computer must be connected wirelessly however. A simple check for this is to validate that the first three numbers of their IPs match (e.g. 192.168.x). This network needs to be internet accessible.

ii) Firewalls

Many firewalls, specifically the built in windows firewall, does not allow network communication without being allowed. Be sure to accept all prompts to allow your applications network access - and you may need to open all the ports explicitly for it to work properly

Figured Depicted below

Image 22

How it can be done

  1. Download the BrassMonkey SDK  from Web
  2. Copy to your own Unity Project
  3. Add the BrassMonkey Prefab to the Unity Scene
  4. Register to the BrassMonkey Website from the BrassMonkey prefab option

Image 23 

5)You will get app key and app id its free

Image 24 

6)Need to save your project as Web Player project.I will host it in Windows Azure

Image 25

Then you are good to go.

Brass Monkey Unity SDK

It is a free version that can be used anywhere in project.

The Brass Monkey® SDK enables your Unity game to become a game console that supports multiple game controller devices to connect simultaneously.  This allows you to have multi-player game experience using a single computer.  Only requirement is the game controllers and the game console computer are on the same WIFI network.  A game controller can be any iOS device or an android device. The Brass Monkey® SDK lets you get many types of input from your game controllers and send commands to your game controller.  You can access the accelerometer information and send commands like vibrate.  You can create game controller schemes for your device.  A game controller scheme is a collection of images you send to the device and display on the device’s screen.  A visual scheme editor is included for creating these schemes.  There are built-in controller schemes and custom controller schemes.  Customer controllers schemes can also be dynamic allowing for the controller to change the display during the game.  The game controller schemes can show pictures and have buttons or other controls that can be used to control your game.  The SDK manages getting the input from these devices.  You can get button push events and track touches enabling many creative ways to control your game.

Controller Mode

It has got 4 modes

  1. Gamepad
  2. Text mode
  3. Navigation
  4. Hold

GamePad

To display your custom control scheme to the user, you can set their device to be in Gamepad mode. This is the default mode of the device, and only needs to be called if you enter a different mode to handle menu or other input elements with different control modes.

C#
//
BMConnection.getInstance().SetControlMode(device, ControlMode.GamePad);

Device Connections Referencing the Controller Devices The BMConnection provides properties to access your devices. If you only need to access a single controller, you can simply use BMConnection.ControllerDevice. This property will be null if there is no device connected.

C#
//
BrassMonkey.Devices.TouchDevice device = BMConnection.ControllerDevice;

If you application has more than one device, you can reference them via the ControllerDevices array property of the BMConnection.ControllerDevice is actually just a reference to ControllerDevices[0].

C#
//
BrassMonkey.Devices.TouchDevice device = BMConnection.ControllerDevice[0];

Device States If you need to be notified when a device becomes available, connects, or disconnect, you can listen for the DeviceStateChange event from the BMConnection.

C#
//
BMConnection.getInstance().DeviceStateChange += new
BrassMonkey.IO.DeviceConnectionStateEvent(OnDeviceStateChange);
public void OnDeviceStateChange (INetConnection connection, BMDevice device, ConnectionState
fromState, ConnectionState toState)
{
switch(toState)
{
case ConnectionState.AVAILABLE:
case ConnectionState.CONNECTED:
case ConnectionState.DISCONNECTED:
break;
}
//

This event is fired when any one of these states occurs, allowing you to easily handle disconnects and newly available devices in your code. An example of how this is done can be seen in BrassMonkey/Demo Assets/SphereManager.cs. Alternatively, you can always check the state of a device by simply calling;

C#
//
ConnectionState state = BMConnection.ControllerDevice.GetConnectionState();

Game Controller Options Controllers can generate button events or track touches. Brass Monkey also supports the multi-touch feature of your iOS or android device. The SDK provides you an event driven layer to receives these commands. The device’s accelerometer position is sent to the game controller. Devices can also receive vibrate commands from the game console. Acceleration To handle acceleration, you can get a Vector3 of the remote devices current orientation by simply calling:

C#
//
Vector3 acceleration = BMConnection.ControllerDevice.acceleration;
//

Touches The iOS device can track up to 5 concurrent touches. Brass Monkey tracks states of these touches in a class called TouchState so that you can track the beginning, movement and end of a touch. Each touch is assigned a unique identification which you can use to monitor positions and updates to the touch. With in the Unity update() function you can access touches:

C#
//
TouchState[] touches = BMConnection.ControllerDevice.touches;

After all update I am with two versions of the game

1)The version that gets installed in the AIO and you are able to play the game using normal touches ,accelerometer,Gyrometer and using the large Canvas of AIO.Break the balls with your will

2)The second version that is accessed through web hosted at Windows Azure and makes your Smartphones as Game controller.  

NEW LEVELS ADDED

Collect the Coins Level

Here You need to use Keyboard as well as touch to Collect the coin.

You will be using the keyboard keys Up,Down,Left  and Right for movements and  Touch for

Breaking Effect.

The figure depicts the scenario.

Image 26

Game Video Link

LINK

Spike and Atom Ball Level 

Adding different feel to the game we add different ball Objects to the game one is Spike Ball and other is Atom Ball both with Splitting capability 

Spike Ball Figure

Image 27

Spike balls are the sharp  spherical balls with the same capability as normal ball  but with different shape.

Atom Ball Figure

Image 28

Atom Ball Lightning effect game Image 1

Image 292nd game Image

Image 30

Game image 3 using the new Aceelerometer Script

Image 31

  Fourth game Image

Image 32

Spike Ball Game Image

Image 33

 Another game image

 Image 34

 Game Videos

LINK1

Robot Kyle Levels

The Robot Kyle is a robot who gets his energy by splitting effect you need to touch and break the

robot and split with Lightning.

Robo Kyle in Figure

Image 35

There will be two Different Levels to Robot Kyle abilities.

i)normal Splitting effect of the robot where you touch and the robot break

Image 36

While in Development Screenshot

Image 37

ii)Another Level in which the robot gets his energy and multiply by splitting. It is connected to  a energy source(Sphere) from which it gets its energy from.

Image 38  

Screenshot2

 Image 39

 

The project structure of Unity after this work

Image 40

Game Video

Normal Splitting Video

LINK1

Energy Generating Effect

LINK2

Samurai Level

Same Splitting effect for Samurai  Soldier

Image 41

Game Screenshot

Image 42

 Game Video Link

LINK

The Script that uses Accelerometer and the flying effect is as Below

  Its in JavaScript
JavaScript
//
#pragma strict
var speed : float = 10.0;

var filter : float = 5.0;

var maxX : float = 10.0;

var minX : float = -10.0;

var maxY : float = 10.0;

var minY : float = -10.0;

private var accel: Vector3;

function Start () {

}

function Update () {
Screen.sleepTimeout = SleepTimeout.NeverSleep;

accel = Vector3.Lerp(accel, Input.acceleration, filter * Time.deltaTime);

var dir = Vector3(-accel.y, accel.x, 0);

if (dir.sqrMagnitude > 1) dir.Normalize();

transform.Translate(dir * speed * Time.deltaTime);

var pos = transform.position;

pos.x = Mathf.Clamp(pos.x, minX, maxX);

pos.y = Mathf.Clamp(pos.y, minY, maxY);

transform.position = pos; 
}
//

BALLS IN BOARD 

Another level added in which you have to touch split and break the ball keep it in Board.Uses the Large canvas

of AIO to  give a great effect plus accelerometer Support added.The ball stay in the board no matter what force

you apply.

Game Screenshot1

Image 43

Game Screenshot2

Image 44

Balls in Thunder 

Another Level added and you have yet another choice to get the splitting effect out of the balls. The Balls get their Thunder effect from a source. Drag the Ball with touch Split it main motto. Have fun

Gamescreenshot1

Image 45

Game Screenshot2

Image 46

Gamescreenshot3

Image 47 

AIO MUST PLAY GAME

  1. A game suitable for large Canvas of the AIO
  2. Different Levels to choose from for any age groups.
  3. Full Touch Support
  4. Good GUI experience
  5. Facebook SDK integrated so that you are able to share your points online socially
  6. SmartPhone acting as GameController to play with
  7. Accelerometer and Gyroscope added features.
  8. EDice Support to be included.

Synopsis 

I am constantly trying to use the Large Canvas of AIO so  there is always an improvement on my previous work.The More time i spend thinking of the specs of the AIO the more ideas come into my mind.All the assetts usedin the project are freely available in Unity and they can be experimented with.I am working on the Mecanim Animation for the Robot and hopefully will be able to integrate with.Still lot of things experimented and do check the game videos they are the real game footage.Till my next update Bye...

More updates to come. 

Points of Interest

Interaction with object using Touch accelerometer inputs etc.

History

  • Version 1.0 Demo prepared.
  • 2nd Demo Uploaded:Article update with Flocking and lightning effect.
  • 3rd Demo Showing the Flocking Effect Uploaded
  • Update for using the smartphone as a Game Controller
  • New Levels of the Game details updated(Robot Kyle introduced)
  • New Levels added with different Ball types to play with.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)