# Play Block Breaker(Unity3D) With Arduino Ultrasonic Sensor

896

7

5

Published

## Introduction: Play Block Breaker(Unity3D) With Arduino Ultrasonic Sensor

in this instructable I will be showing you guys how to make a block breaker game and play it using an ultrasonic sensor from arduino which will be used as a proximity detector to moe our paddle left and right

## Step 1: Get Your Tools!

you will need

1- Ultrasonic sensor

2- 4 male to female wires

3- a flat surface tool, could be a book, I used a toy racket

## Step 2: Connect Your Components

simple connect a ground and 5 volt wires to your ultrasonic and attach 2 wires to your Trig and Echo ports, I used pins 4 and 5 respectivley

## Step 3: Lets Code Arduino :)

we need to alternate between making sound(Trig) and receiving sound(Echo) to measure the distance using the following formula

distance in cm = calculatedTime * 343.2 / 20000;

and use the following code:

const int TRIG = 5;
const int ECHO = 4;

void setup (){ Serial.begin(9600); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); }

void loop (){ int data = GetUltra(TRIG,ECHO); Serial.write( data ); delay(20);

}

double GetUltra ( int trig , int echo){

digitalWrite(trig , LOW); delayMicroseconds(2); digitalWrite(trig, HIGH); delayMicroseconds(8); digitalWrite(trig, LOW);

double distance = ( pulseIn(echo, HIGH) )* 343.2 / 20000; return distance; }

## Step 4: Determine the Range of Motion

int this part we want to determine what is the distance from and to the ultrasonic that will correspond to the play field in unity, in other words, at what distance away from the ultra sonic I want the paddle to reach left most corner and at what distance I want the paddle to be at the right most corner

I choose 5-25 cm

## Step 5: Lets Code in Unity!

please watch the video in the perivous step for instructions, or you can find a tutorial on youtube how to make a paddle move in blockbreaker

## Step 6: Lets Receive Data From Arduino and Move Our Paddle :)

the final code in unity :

using UnityEngine;
using System.Collections; using System.IO.Ports; public class paddel1 : MonoBehaviour { public float distance;

SerialPort stream = new SerialPort(@"\\.\"+"COM11",9600); // Use this for initialization void Start () { stream.Open(); stream.ReadTimeout = 25; } // Update is called once per frame void Update () {

Vector2 temp = transform.position; if (stream.IsOpen) {

try {

data = Mathf.Clamp(data, 5, 25);

data -= 5; data /= 20; data *= 10; data -= 5;

temp.x = data;

} catch (System.Exception) {

Debug.Log("timeout");

}

transform.position = temp;

}

} }

## Recommendations

• ### Arduino Class

70,628 Enrolled

## 5 Discussions

how did you set the range in arduino? it's not clear how (or even if) you did. !

Great Potential. Subscribed to your channel.

i also like to make application with arduino and unity.

Keep it up.