Prerequisites
This project assumes you are familiar with the basic functionality of Unity. You should also review the following before moving on:
Setup
All you need for this project is the Getting Started Kit.
Configure Unity
In order to use Phidgets with Unity, you have to configure your project. Follow the instructions below.
Step 1
Download a copy of the Phidget libraries and unzip it as shown.
Step 2
Next, open Unity and create a new 3D project. Name it Phidgets_Unity and place it in the location of your choice.
Step 3
Navigate to the file you previously unzipped and import Phidget22.NET.dll and phidget22.dll as shown.
Note: If you are developing on macOS, you do not need to import phidget22.dll
Create Environment
Now that your project is configured, you can create your environment.
Step 4
With the sphere selected, navigate to Component > Physics > Rigidbody to add a Rigidbody component.
Write Code (C#)
Copy the code below into your BallScript file.
using UnityEngine;
using Phidget22;
public class BallScript : MonoBehaviour
{
private Rigidbody rb;
DigitalInput redButton;
bool shouldJump = false;
//Button Event
void RedButton_StateChange(object sender, Phidget22.Events.DigitalInputStateChangeEventArgs e)
{
shouldJump = e.State;
}
// Start is called before the first frame update
void Start()
{
//Connect Rigidbody
rb = GetComponent<Rigidbody>();
//Create
redButton = new DigitalInput();
//Address
redButton.HubPort = 0;
redButton.IsHubPortDevice = true;
//Subscribe to Events
redButton.StateChange += RedButton_StateChange;
//Open
redButton.Open(1000);
}
// Update is called once per frame
void Update()
{
//Use your Phidgets
if (shouldJump)
{
shouldJump = false;
Vector3 jump = new Vector3(0.0f, 250.0f, 0.0f);
rb.AddForce(jump);
}
}
//Required for Unity and Phidgets
private void OnApplicationQuit()
{
redButton.Close();
redButton.Dispose();
}
}
Run Your Program
When you run your code and press the red button, you will see your ball jump.
Code Review
When using buttons with Unity, it's a good idea to use events. Events will allow you to easily determine when a button has been pushed or released. Polling can also be used, however, extra code will be required.
Practice
- Add new functionality to your program using the green button. When the green button is pressed, try adding horizontal movement.