Arduino code
int carRotation=0; //variable to read the values from the potentiometers
int carSpeed=0;
void setup() {
Serial.begin(9600); //start the serial communication
pinMode(A0,INPUT); //initialize the potentiometers inputs
pinMode(A1,INPUT);
}
void loop() {
carRotation = analogRead(A0); //read the values of the potentiometers - between 0 and 1023
carSpeed = analogRead(A1);
Serial.print(map(carSpeed,0,1023,-100,100)); //scale it to use it with the car speed
Serial.print(",");
Serial.println(map(carRotation,0,1023,-100,100)); //scale it for the car rotation
delay(25);
}
Unity code
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using System.IO.Ports; //Library to read our ardunio data
using System.Collections; //to use Ienumarator in our code
namespace UnityStandardAssets.Vehicles.Car
{
[RequireComponent(typeof (CarController))]
public class CarUserControl : MonoBehaviour
{
private CarController m_Car; // the car controller we want to use
SerialPort seri = new SerialPort("COM6",9600);//define our port
private void Awake()
{
// get the car controller
seri.Open();//open our port
StartCoroutine(ReadDataFromSerialPort());//start loop
m_Car = GetComponent<CarController>();
}
IEnumerator ReadDataFromSerialPort(){
while(true){//loop
string[] values = seri.ReadLine ().Split (',');//we split our string value by , because we write string as carspeed,cartotation in our ardunio codes
v = (float.Parse(values[0])) / 100;
h = (float.Parse (values [1])) / 100;
yield return new WaitForSeconds (.05f);//waiting seconds to read data. It should be same as ardunio code loop delay
}
}
float h;//horizontal (car direction)
float v;//vertical (car speed)
private void FixedUpdate()
{
// pass the input to the car!
//Close old codes which created by unity team
//float h = CrossPlatformInputManager.GetAxis("Horizontal");
//float v = CrossPlatformInputManager.GetAxis("Vertical");
#if !MOBILE_INPUT
float handbrake = CrossPlatformInputManager.GetAxis("Jump");
m_Car.Move(h, v, v, handbrake);
m_Car.Move(h, v, v, 0f);
}
}
}
oxoxxooxoxoxoxox
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Vehicles.Car
{
[RequireComponent(typeof (CarController))]
public class CarUserControl : MonoBehaviour
{
private CarController m_Car; // the car controller we want to use
private void Awake()
{
// get the car controller
m_Car = GetComponent<CarController>();
}
private void FixedUpdate()
{
// pass the input to the car!
float h = CrossPlatformInputManager.GetAxis("Horizontal");
float v = CrossPlatformInputManager.GetAxis("Vertical");
#if !MOBILE_INPUT
float handbrake = CrossPlatformInputManager.GetAxis("Jump");
m_Car.Move(h, v, v, handbrake);
m_Car.Move(h, v, v, 0f);
}
}
}
Comments