- Home /
very long LAG in my unity game using arduino
im a first time user of unity3d and ive seen a tutorial on a car simulation using arduino and unity . i followed every steps in the tutorial. i even copy and paste the code for the unity . and it's already running but the problem is it has a 30 seconds delay before reading the inputs that my arduino is sending. here are the codes that im using and here is the tutorial that ive been follwing. hope someone could help me. i really dont know what to do. https://www.youtube.com/watch?v=N9RhSa8oMD8&t=414s
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(50);
}
car user control 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);
#else
m_Car.Move(h, v, v, 0f);
#endif
}
}
}
Your answer
Follow this Question
Related Questions
Arduino Unity3d FPS drop after twisting Potentiometer 0 Answers
unity to serial ports ( blink LED ) 0 Answers
Arduino serial delegate help 1 Answer
transform.rotation = ... reacts slow 2 Answers
Need Help Connecting Arduino to Unity 0 Answers