I am trying to build a car simulator in steam VR, I want the car and wheel to rotate by 30 degrees when I rotate the steering by 360, The problem I am facing is when I rotate the steering the 2nd time the car resets back to its original rotation angle that is at 0 to 30 degree again. How can I increment the angles. Below is the code that I tried to increment the angles but it not workingas the posFinal and posInitial are only varying from -0.4 to 0.4.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR.InteractionSystem;
[RequireComponent(typeof(Interactable))]
public class RotateWheel : MonoBehaviour {
public Transform Steer;
public Transform Wheel2;
public Transform car;
float scalingFactor = 0.5f;
public float posInitial; public float posFinal; float temp;
void Start()
{
posInitial = 0f;
posFinal = Steer.transform.rotation.y;
car.transform.eulerAngles = new Vector3(0, 0, 0);
Wheel2.transform.eulerAngles=new Vector3(0,0,0);
}
private void FixedUpdate()
{
Wheel2.transform.eulerAngles = new Vector3(-0, ((car.transform.eulerAngles.y+(posFinal-posInitial) )*30f/360), 0);
car.transform.rotation = Quaternion.Slerp(Wheel2.transform.rotation, Quaternion.identity, (Time.deltaTime *5) / scalingFactor);
temp = posInitial;
posInitial = posFinal;
posFinal = Steer.transform.rotation.y;
}
Related
I made my object move in one direction and reset z position to 0 when it reaches position 10. But position z does not returning to 0 when it reaches 10.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class NewBehaviourScript : MonoBehaviour
{
float z = 1.0F;
void Update()
{
if (z < 10.0f)
{
//move object forward
transform.Translate(0,0,z * Time.deltaTime * 0.5F);
}
else
{
z = 0;
}
}
}
The issue is that .Translate method moves an object by a specific vector. It doesn't assign a set position.
If you want to reset z position of a transform, assign a new vector to .position property containing the original x and y values and a 0 as the last parameter.
Here's a fixed up version of your code:
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private const float Speed = 1.0f;
private void Update()
{
if (transform.position.z < 10.0f)
{
// Moving object forward
transform.Translate(0, 0, Speed * Time.deltaTime);
}
else
{
transform.position = new Vector3(
transform.position.x,
transform.position.y,
0f);
}
}
}
I want to move main camera slowly from one point to another point when a button is pressed. This button calls the method which has the code to move the camera.
I have tried using the Lerp method but the camera position is changing so fast that when I click on the button camera directly shifting to a new position. I want the camera to move slowly to a new position.
Below is my code, can anyone please help me with this.
=========================================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
public GameObject cam;
Vector3 moveToPosition;// This is where the camera will move after the start
float speed = 2f; // this is the speed at which the camera moves
public void move()
{
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
float step = speed * Time.deltaTime;
cam.transform.position = Vector3.Lerp(cam.transform.position, moveToPosition, step);
cam.transform.position = moveToPosition;
}
}
It's easier to use lerp with frames and you need to use it in an Update function. Try using the example from the Unity docs:
public int interpolationFramesCount = 45; // Number of frames to completely interpolate between the 2 positions
int elapsedFrames = 0;
void Update()
{
float interpolationRatio = (float)elapsedFrames / interpolationFramesCount;
Vector3 interpolatedPosition = Vector3.Lerp(Vector3.up, Vector3.forward, interpolationRatio);
elapsedFrames = (elapsedFrames + 1) % (interpolationFramesCount + 1); // reset elapsedFrames to zero after it reached (interpolationFramesCount + 1)
Debug.DrawLine(Vector3.zero, Vector3.up, Color.green);
Debug.DrawLine(Vector3.zero, Vector3.forward, Color.blue);
Debug.DrawLine(Vector3.zero, interpolatedPosition, Color.yellow);
}
Try using smooth damp.
Here is the new code you should try:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
Vector3 matric;
public GameObject cam;
Vector3 moveToPosition;
float speed = 2f;
bool move_ = false;
void Update(){
if(move_){
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
cam.transform.position =
Vector3.SmoothDamp(cam.transform.position,
moveToPosition,
ref matric, speed);
}
}
public void move()
{
move_ = true;
}
}
I have been trying to simulate the gyroscope behavior in unity by using accelerometer and compass. So far I have achieved some functionality but it still has a lag; a delay of response. It does not change the view as fast as the tilt of the mobile phone. Any help is appreciated and thank you in advance.
Note: Z axis rotation is still not added.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GyroSimulator : MonoBehaviour {
float zValue;
float zValueMinMax = 5.0f;
Vector3 accelometerSmoothValue;
//Smooth Accelerometer
public float AccelerometerUpdateInterval = 1.0f / 100.0f;
public float LowPassKernelWidthInSeconds = 0.001f;
public Vector3 lowPassValue = Vector3.zero;
void Start () {
Screen.orientation = ScreenOrientation.LandscapeLeft;
Input.compass.enabled = true;
}
//Update is called once per frame
void Update () {
//Set Z Min Max
if (zValue < -zValueMinMax)
zValue = -zValueMinMax;
if (zValue > zValueMinMax)
zValue = zValueMinMax;
accelometerSmoothValue = LowPass();
zValue += accelometerSmoothValue.z;
transform.rotation = Quaternion.Slerp(
transform.rotation,
Quaternion.Euler(
-zValue*5.0f,
Input.compass.magneticHeading,
0
),
Time.deltaTime*5.0f
);
}
Vector3 LowPass()
{
Vector3 tilt = Input.acceleration;
float LowPassFilterFactor = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds;
lowPassValue = Vector3.Lerp(lowPassValue, tilt, LowPassFilterFactor);
return lowPassValue;
}
}
I'm using an Array to multiply a 3D object randomly in the space, so i'm getting a lot of nice objects floating randomly over the y, x and z axes.
This object has also an Audio Source with a sound attached to it, which means that after applying the random-array-positioning I get different objects with different Audio Sources as well.
The problem is that I'm also changing the scale of those objects, which it's working super well, but the size/scale/radius of the Audio Source it's not changing at all.
How can I change the scale of the objects and change the size/scale/radius of the Audio Source at the same time, to match both equally or proportionally in size?
I'm looking here but I Can't figured out.
https://docs.unity3d.com/ScriptReference/AudioSource.html
This is the code that I'm using for:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class multipleObjectsGrandes : MonoBehaviour {
public GameObject prefabGrandes;
public GameObject[] gos;
public int cantidad;
public float minScaleObj;
public float maxScaleObj;
void Awake()
{
gos = new GameObject[cantidad];
for(int i = 0; i < gos.Length; i++)
{
//Position
Vector3 position = new Vector3(Random.Range(-40.0f, 40.0f), Random.Range(-40.0f, 40.0f), Random.Range(-40.0f, 40.0f));
GameObject clone = (GameObject)Instantiate(prefabGrandes, position, Quaternion.identity);
//Scale
clone.transform.localScale = Vector3.one * Random.Range(minScaleObj, maxScaleObj);
//Rotation
clone.transform.rotation = Quaternion.Euler(Random.Range(0.0f, 360.0f), Random.Range(0.0f, 360.0f), Random.Range(0.0f, 360.0f));
gos[i] = clone;
}
}
}
This is the code that i'm using to multiply objects:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class multipleObjectsGrandes : MonoBehaviour
{
public GameObject prefabGrandes;
public GameObject[] cuerpos;
public int cantidad;
public float minScaleObj;
public float maxScaleObj;
public float escalaMax;
void Awake ()
{
cuerpos = new GameObject[cantidad];
for (int i = 0; i < cuerpos.Length; i++) {
//Position
Vector3 position = new Vector3 (Random.Range (-40.0f, 40.0f), Random.Range (-40.0f, 40.0f), Random.Range (-40.0f, 40.0f));
GameObject clone = (GameObject)Instantiate (prefabGrandes, position, Quaternion.identity);
//Scale
clone.transform.localScale = Vector3.one * Random.Range (minScaleObj, maxScaleObj);
//Rotation
clone.transform.rotation = Quaternion.Euler (Random.Range (0.0f, 360.0f), Random.Range (0.0f, 360.0f), Random.Range (0.0f, 360.0f));
escalaMax = clone.transform.localScale.x;
//Debug.Log(escalaMax);
}
}
}
Everything is ok here when I'm debugging "escalaMax" in the console.
The variable "escalaMax" is the one that i'm passing to the other script which is inside the object that I'm multiplying which has an audioSource attached to it. This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent (typeof(AudioSource))]
public class AudioRandomPitch : MonoBehaviour
{
public float startingPitch = 1;
public float minPitchRandom = 0;
public float maxPitchRandom = 0;
AudioSource audio;
public float audioScale;
void Start ()
{
startingPitch = Random.Range (minPitchRandom, maxPitchRandom);
audio = GetComponent<AudioSource> ();
audio.pitch = startingPitch;
GameObject theMultiplicator = GameObject.Find ("Multiplicador_deCuerpos");
multipleObjectsGrandes multiplicatorScript = theMultiplicator.GetComponent<multipleObjectsGrandes> ();
multiplicatorScript.escalaMax = audioScale;
//this is not working
audio.maxDistance = audioScale;
Debug.Log(audioScale);
}
}
Here I'm first saving the value coming from the other script escalaMax inside the new variable audioScale.
The problem now is when I try to pass the audioScale value to the audio.maxDistance var.
I'm super close I know, but as you can see, i'm not a really good programmer and I'm probably doing something stupidly wrong... :/
Thanks for the help!
I'm using the standard camera2DFollow script that comes with Unity 5. But I have a problem with the position of the camera. I've rotated my main camera and it looks like this now.
You see that my player is on top of the screen instead of the middle.
This is the default script in C# for the people who don't have it.
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class Camera2DFollow : MonoBehaviour
{
public Transform target;
public float damping = 1;
public float lookAheadFactor = 3;
public float lookAheadReturnSpeed = 0.5f;
public float lookAheadMoveThreshold = 0.1f;
private float m_OffsetZ;
private Vector3 m_LastTargetPosition;
private Vector3 m_CurrentVelocity;
private Vector3 m_LookAheadPos;
// Use this for initialization
private void Start()
{
m_LastTargetPosition = target.position;
m_OffsetZ = (transform.position - target.position).z;
transform.parent = null;
}
// Update is called once per frame
private void Update()
{
// only update lookahead pos if accelerating or changed direction
float xMoveDelta = (target.position - m_LastTargetPosition).x;
bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;
if (updateLookAheadTarget)
{
m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
}
else
{
m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
}
Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);
transform.position = newPos;
m_LastTargetPosition = target.position;
}
}
}
I want to change the Y to a +3 of the current position. So if my camera is on Y 2 than put it on Y 5. (This makes it so the player is in the middle and not on the top).
Thanks for the help!
You can do this by adding 3 to the camera's position at the end of each frame but I recommend against it.
What I would do, is create an empty object, name it "PlayerCameraCenter" and make the player parent to this object; then place the camera center wherever you want relative to the player, like y = 3, and make the camera follow this object instead of the player.
This way you can easily change the position of the camera, through the editor without fiddling with code.