Find collision time given distance and speed - unity3d

Suppose I have an object A at position x = 0 and object B at position x = 16.
Suppose A have this code:
public class Move : MonoBehaviour
{
float speed = 0.04f;
Update()
{
transform.Translate(speed, 0, 0);
}
}
My question is: how to evaluate how many seconds (precisely) will it take for A to collide with B?
If I apply the formula S = S0 + vt, it won't work correctly, because I don't know how to measure how many frames it will pass in a second to exactly measure what speed is.

First of all you shouldn't do that. Your code is currently framerate-dependent so the object moves faster if you have a higher framerate!
Rather use Time.deltaTime
This property provides the time between the current and previous frame.
to convert your speed from Unity Units / frame into Unity Units / second
transform.Translate(speed * Time.deltaTime, 0, 0);
this means the object now moves with 0.04 Unity Units / second (framerate-independent).
Then I would say the required time in seconds is simply
var distance = Mathf.Abs(transform.position.x - objectB.transform.position.x);
var timeInSeconds = distance / speed;
Though .. this obviously still assumes by "collide" you mean at the same position (at least on the X axis) .. you could also take their widths into account since their surfaces will collide earlier than this ;)
var distance = Mathf.Abs(transform.position.x - objectB.transform.position.x) - (objectAWidth + objectBWidth);
var timeInSeconds = distance / speed;

Related

How to move an object by a certain angle over a period of time in a circle [duplicate]

I a new here and i try to start working with Unity Engine.
Could somebody explain me, how works Quaternion.Slerp? Because I want to rotate some object in different angles 90, 180 and 270. My code you can see below. Unfortunately when I add 180 degrees, object make crazy things and than put rotation to (0, 180, 180) for this game object. I would like to get (180,0,0)
public float speed = 0.1F;
private float rotation_x;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
rotation_x = transform.rotation.eulerAngles.x;
rotation_x += 180;
}
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(rotation_x, transform.eulerAngles.y, transform.eulerAngles.z), Time.time * speed);
}
Most examples out there including Unity examples from their official website are using Lerp in the wrong way. They didn't even bother to describe how it works in the API documentation. They just starch it in the Update() function and call it a day.
Mathf.Lerp, Vector3.Lerp, and Quaternion.Slerp work by changing from one position/rotation to another with the t value(last parameter) being passed in.That t value is also know as time.
The min of the t value is 0f and the max is 1f.
I will explain this with Mathf.Lerp to make it easier to understand. The Lerp functions are all the-same for both Mathf.Lerp, Vector and Quaternion.
Remember that Lerp takes two values and returns values between them. If we have a value of 1 and 10 and we do Lerp on them:
float x = Mathf.Lerp(1f, 10f, 0f); will return 1.
float x = Mathf.Lerp(1f, 10f, 0.5f); will return 5.5
float x = Mathf.Lerp(1f, 10f, 1f); will return 10
As you can see, the t(0) returns the min of the number passed in, t(1) returns the max value passed in and t(0.5) will return mid point between the min and the max value. You are doing it wrong when you pass any t value that is < 0 or > 1. That code in you Update() function is doing just that. Time.time will increase every second and will be > 1 in a second, so you have problems with that.
It recommended to use Lerp in another function/Coroutine instead of the Updated function.
Note:
Using Lerp has a bad side of it when it comes to rotation. Lerp does not know how to rotate Object with the shortest path. So bear that in mind. For example, you have an Object with 0,0,90 position. Lets say you want to move the rotation from that to 0,0,120 Lerp can sometimes rotate left instead of right to reach that new position which means it take longer to reach that distance.
Let's say we want to make the rotation (0,0,90) from whatever the current rotation is. The code below will change the rotation to 0,0,90 in 3 seconds.
ROTATION OVER TIME:
void Start()
{
Quaternion rotation2 = Quaternion.Euler(new Vector3(0, 0, 90));
StartCoroutine(rotateObject(objectToRotate, rotation2, 3f));
}
bool rotating = false;
public GameObject objectToRotate;
IEnumerator rotateObject(GameObject gameObjectToMove, Quaternion newRot, float duration)
{
if (rotating)
{
yield break;
}
rotating = true;
Quaternion currentRot = gameObjectToMove.transform.rotation;
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
gameObjectToMove.transform.rotation = Quaternion.Lerp(currentRot, newRot, counter / duration);
yield return null;
}
rotating = false;
}
INCREMENTAL ANGULAR ROTATION OVER TIME:
And to just rotate the Object to 90 in z axis, the code below is a great example of that. Please understand there is a difference between moving Object to new rotational point and just rotating it.
void Start()
{
StartCoroutine(rotateObject(objectToRotate, new Vector3(0, 0, 90), 3f));
}
bool rotating = false;
public GameObject objectToRotate;
IEnumerator rotateObject(GameObject gameObjectToMove, Vector3 eulerAngles, float duration)
{
if (rotating)
{
yield break;
}
rotating = true;
Vector3 newRot = gameObjectToMove.transform.eulerAngles + eulerAngles;
Vector3 currentRot = gameObjectToMove.transform.eulerAngles;
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
gameObjectToMove.transform.eulerAngles = Vector3.Lerp(currentRot, newRot, counter / duration);
yield return null;
}
rotating = false;
}
All my examples are based on frame-rate of the device. You can use real-time by replacing Time.deltaTime with Time.delta but more calculation is required.
Before anything, you can't add 180 on euler angles like that, and that's mainly what is causing your problem. You'd better use quaternion directly instead, or work on the transform itself.
You can think of a quaternion as an orientation in space. In contrary to what have been said, I do recommend learning how to use them if you can. However, I don't recommend using euler angles at all... as they're suject to different writing conventions, and will fail sometimes. You can look at 'gimbal lock' if you want details about that.
Simply a slerp or lerp (standing for spherical linear interpolation, or linear interpolation respectively) is a way to interpolate (go from one orientation to another, by increasing t from 0 to 1, in a coroutine or anywhere else) between orientation A and B. The difference between the two is that the slerp is giving you the shortest path from A to B.
In the end, when t = 1, lerp(A,B,t) and slerp(A,B,t) will give you B.
In your case, if you want to instantly rotate an object in space to a specific orientation, I suggest you use Quaternion.AngleAxis which is the most forward way to describe mathematically a quaternion.
If you want to add a rotation, say 90° to you actual orientation (without animation between the two), you can do something like this :
transform.rotation *= Quaternion.AngleAxis(axis_of_rotation, angle)
or use transform.rotate (depending on the parameters, it can be a right multiply, or left : local, or world transform).
Programmers' answer is detailling how to animate your transform. But I do suggest you to investigate quaternion themselves, as it will give you global understanding of space transforms.

Quaternion correction

I'm trying to implement network correction for a client simulated Rigidbody. 30 times a seconds I get the target rotation from which I calculate the rotation correction. Then I apply this correction over a number of frames.
Network update:
rotationCorrection = receivedRotation * Quaternion.Inverse(transform.rotation);
Every frame:
var a = Mathf.Min(1, Time.deltaTime * 8);
var final = Quaternion.Slerp(transform.rotation, transform.rotation * rotationCorrection, a);
var actualCorrection = final * Quaternion.Inverse(transform.rotation);
rotationCorrection *= Quaternion.Inverse(actualCorrection);
//rotationCorrection = Quaternion.Slerp(rotationCorrection, Quaternion.identity, a); // First try
_rigidbody.MoveRotation(final);
The reason I don't just interpolate the current rotation to the corrected on is the GameObject contains a Rigidbody which should simulate the object in addition to the correction.
This does work sometimes (at least the first try version), except at angles between roughly -90 and 90. I suspect its the code to slerp the rotationCorrection to identity.
(work in progress since the question was not 100% clear)
The subtraction formulae yield wrong results. Please try using euler, subtract the angles and you can make the desired quaternion.
Are you sure you don't need Lerp instead of Slerp?
Anyway final should not use Lerp or Slerp.
If as final you want transform.rotation * rotationCorrection (which is the current rotation plus the correction), then just use it as that. Multiplications actually add the rotation.
Lerp and Slerp are to be used with an a parametric to time, where a==0 will return the starting rotation, a==1 will return the final rotation. So a should be scaled with time. If, on the other hand, the network correction is exactly what you need and you get it at specific fixed-time updates, then without any Lerp, might as well try transform.rotation = transform.rotation*rotationCorrection.
rotationCorrection = receivedRotation * Quaternion.Inverse(transform.rotation);
What this does is return a rotation that starts from receivedRotation and ends to the opposite rotation of the current transform rotation. So neither the start nor the end point match with the current one.
so:
You set a final quaternion as currentRot * change
a starting as currentRot
and then update transform.rotation by making it = (S)Lerp with start, end and a parameter that equals 0 at starting time and 1 at ending time.
The network update was wrong. Corrected:
rotationCorrection = Quaternion.Inverse(transform.rotation) * receivedRotation;

Rigidbody.Moveposition issue

I'm trying to make a type of projectile with Rigidbody:
private void FiredAsProjectile(GameObject target)
{
Vector3 moveVector = Vector3.Zero;
float velMod = 8f // A placeholder value to later calculate with mass / velocity
if(target != null)
{
moveVector = (target.transform.position - transform.position);
m_rb.MovePosition(transform.position + moveVector * Time.deltaTime * velMod);
}
}
This is updated via FixedUpdate upon calling this method somewhere else. I have a few things I needed this to behave: to have velocity output and move to a position, not direction.
However, I'm getting a weird outcome. Even though this object moves as a kinematic rigidbody and its interpolation is set to None this object slows down before reaching the target vector as if it has interpolation. Let's say I wanted a bullet to be fired from the barrel and fly to a point in world instead of direction, that's what I wanted this object to behave like, but not quite so.
Am I missing something or misunderstanding something?
Is there a better way to move this kinematic rigidbody whilst still outputting rigidbody.velocity and still collide?
This happens because you don't Normalize the moveVector.
To explain why this happens, we'll suppose that Time.deltaTime = 0.01 every step:
At t0 time, let's say that the distance between the moving object (in x = 0) and the target object (x = 100) is 100.
The argument of MovePosition is 0 + 100*8*.01 = 8 and the object is moved accordingly to this new position (since you said it's Kinematic without interpolation)
At t1 time, moveVector = 100-8 = 92
The new argument now is 8 + 92*8*.01 = 15.36
Notice that between t0 and t1 you moved 8 units, whereas between t1 and t2 you moved only 7.36 units. So, the more your moving object is near the target object, the less you'll move the object, giving the effect of "slowing down" (and moreover it'll never reach the target object, you'll stop at a distance equal to the minimum floating number precision).
In order to fix this, you just need to normalize the moveVector, i.e. making its module fixed every step. So, just add this line:
moveVector = (target.transform.position - transform.position);
moveVector.Normalize();
m_rb.MovePosition(transform.position + moveVector * Time.deltaTime * velMod);
and the distance moved every step will always be the same regardless of distance.

finding the force needed based on distances between objects

Trying to programatically set the force based on the distance of the selected object, and another static object.
To understand this better I am making a golf game, I have forced being applied to ball already done but I am manually setting the force at this point. Right now I am trying to build some pseudo-code for how I can accomplish this. I do not have a lot of experience with physics so anything will help here. But basically I have a golfer who selects an area that he would like to hit it to. So once selected, I will grab the location of the selection, obviously find the difference via (selected.transform.position - golfer.transform.position) but now I am a little stuck on what to do next. How can I find the force needed to get to the selected location?
here's some current code in case it helps
var target : Transform;
var speed : float;
var force : float;
var angle = 50;
var i = 1;
function FixedUpdate()
{
if (target == null)
target = GameObject.FindWithTag("Hole").transform;
}
function Hit()
{
var torque = Vector3(Input.GetAxis("Vertical"), 0, -Input.GetAxis("Horizontal"));
var targetRotation = Quaternion.LookRotation (target.position-transform.position,Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation,targetRotation,8);
transform.eulerAngles.x = -angle;
rigidbody.AddTorque(torque.normalized*speed);
rigidbody.AddForceAtPosition (transform.forward * speed * force,target.position, ForceMode.VelocityChange );
}
You will need a few things.
Angle of Force theta
Mass of object m
On the x-axis:
Acceleration a
Initial velocity vi
Final velocity vf
Distance d
Time to travel t
On the y-axis:
Acceleration a = gravity
Initial velocity vi_y
Final velocity vf_y
Height traveled h
Then use the equations for Kinematics and F=ma to find the force.
Your goal is to combine what you know, mass of object, distance, etc. and apply the equations of kinematics to find the acceleration needed on the x-axis. Then you will plug in that acceleration and the mass to F=ma to find the Force.

Instantiate gameobject between 2 objects in unity 3d

I have 2 objects. It will be in various direction and distance.
How can i instantiate objects between them with a specific distance.
var centerLocation : Vector3 = Vector3.Lerp(object2.transform.position - object1.transform.position, 0.5);
Vector3.Lerp will determine the Vector3 location between 2 Vector3s at a specified percentage. 0.5 = 50%.
My suggestion would be to calculate the vector between the two objects, like this
Vector3 objectLine = (object2.transform.position - object1.transform.position);
Store the magnitude of that vector
float distance = objectLine.magnitude;
Then, normalise the vector;
objectLine = objectLine.normalized;
Iterate through the line, instanciating the object you want to create a specific distances
Vector3 creationPoint = object1.transform.position;
float creationPointDistance = (object1.transform.position -
object1.transform.position);
while(creationPointDistance < distance)
{
creationPoint += objectLine * NEW_OBJECT_DISTANCE;
creationPointDistance = (object1.transform.position -
object1.transform.position);
if(creationPointDistance < distance)
{
objects.Add((GameObject)Instanciate(newObject, creationPoint,
new Vector3(0.0f,0.0f,0.0f)));
}
}
What that will do is set the initial point to be object1's position. It will then move a set distance along the vector between object 1 and object 2, check it's within the two objects, and if it is, instanciate the object, storing it in a list of gameobjects.
That hopefully should do it. I don't have Unity (or any IDE) in front of me to check the syntax.