I need the Player to follow the moving Target and stop exactly when it reaches the Target.
The Player has to reach the Target almost instantaneously in every frame, so i need a high speed way to do it.
I couldn't use Transform.translate because there's a lot of physics implementations in my game and using Transform.translate or movetowards made the physics buggy.
Is there any physics based way to follow the target? velocity, AddForce, anything? For a 2D game.
Any leads would be greatly appreciated! Thank You!
If you have a Rigidbody2D you want to follow another object, the Rigidbody2D.MovePosition is the proper way to move it.
Do the following:
1.Disable gravity by setting the "Gravity Scale" to 0.
2.Change the BodyType to Kinematic.
3.You can now move the Rigidbody object to follow another GameObject with the Rigidbody2D.MovePosition function. See code below. This should be done in the FixedUpdate function and with Time.fixedDeltaTime instead of Time.deltatime.
Finally, if you still get jerky movement, change Interpolate option from None to Interpolate or Extrapolate. I would also suggest reducing the speed variable below.
//Object to follow
public Transform target;
//Rigidbody to move
public Rigidbody2D rb2d;
public float speed = 7.0f;
//Distance to start moving
public float minDistance = 0.09f;
void FixedUpdate()
{
//Find direction
Vector3 dir = (target.transform.position - rb2d.transform.position).normalized;
//Check if we need to follow object then do so
if (Vector3.Distance(target.transform.position, rb2d.transform.position) > minDistance)
{
rb2d.MovePosition(rb2d.transform.position + dir * speed * Time.fixedDeltaTime);
}
}
Changing the velocity directly is always a bad practice and should be avoided. Instead always work with AddForce.
I would calculate the distance between the target and the body and add a force based on that distance.
var dif = target.transform.pos - body.transform.pos;
bodyRigid.AddForce(dif * multiplier * Time.deltatime);
The only problem that comes with that solution might be the fact that the body 'shakes' around the target once its to close.
You could avoid this by checking if the body is close to target and then freezing it.
var dif = target.transform.pos - body.transform.pos;
if(dif.magnitude > 1) {
bodyRigid.AddForce(dif * multiplier * Time.deltatime);
} else {
bodyRigid.velocity = Vector2.zero;
}
Although I said that setting the velocity directly is a bad habit, using it to just freeze the body should be fine. I have no idea whether that might break your other physics that you use in your game, duo the fact that that just strait up freezes your object.
You can also change the distance (1 in the if statement) that it needs in order to freeze, just play around with it a bit and find a value that fits the game
Related
I have a big number of objects which I would like to move and rotate in Update() method. The movement part is pretty simple. The issue comes with rotation performance. Operations with euler angles are quite expensive and I want to optimize this part.
I've tried using both
transform.rotation.eulerAngles += _rotationDirection * Time.deltaTime;
and
transform.Rotate(_rotationDirection * Time.deltaTime);
But they are expensive to call.
Since objects have a constant rotation value, I tried this:
private void Awake()
{
_rotationDelta = Quaternion.Euler(_rotationDirection * _rotationSpeed);
}
private void Update()
{
transform.rotation *= _rotationDelta;
}
This seems to be more performant but my issue now is that I don't know how to link Time.deltaTime to this because you can't just write
transform.rotation *= _rotationDelta * Time.deltaTime;
So, my question is, what is the fastest way to rotate an object if the rotation delta is constant during object's lifetime?
There are two big issues:
One call per frame (Update Method)
Unoptimized Arithmetic (Transform.rotate)
Use RigidBody instead!
Explanation:
The way Transform.Rotate works is that it calculates rotation and returns rotation as Quaternion which can be then assigned to the rotation value.
Calls in Update method are a big performance issue as they're called before each frame is dropped, and can cause stutters or constantly low fps.
The fix for all of this is simply, RigidBody.
You should set drag and angular drag to 0, so that the rotation doesn't slow down.
You can also freeze position if you will not be moving your objects.
The call will simply be once in the start of the game (in Start() method):
int angularPower = 5;
void Start(){
GetComponent<Rigidbody>().AddTorque(angularPower, 0, 0);
}
Im trying to make a Hill Climb Racing clone, saw a video on it and followed the tutorial:
https://www.youtube.com/watch?v=DgG9us3QkTE
As mentioned I followed the tutorial except for some little details that a couple of comments stated.
Instead of creating a wheel joint for each tire, I moved the wheel joints to the empty CarController and attached the joints to each tire.
In the code instead of writing "-movement" i wrote "movement".
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarControllerS : MonoBehaviour
{
public Rigidbody2D carRigidbody;
public Rigidbody2D bTire;
public Rigidbody2D fTire;
public float speed = 20;
private float movement;
public float carTorque = 10;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
movement = Input.GetAxis("Horizontal");
}
private void FixedUpdate ()
{
bTire.AddTorque(movement * speed * Time.fixedDeltaTime);
fTire.AddTorque(movement * speed * Time.fixedDeltaTime);
carRigidbody.AddTorque(movement * carTorque * Time.fixedDeltaTime);
}
}
The problem now is that when i press the arrow up it does not move forward (the car). How and why is this happening.
Thanks in advance // a desperate noob programmer
You have nothing in your script that applies a linear, translational force, only rotation force (ie, torque). This was what derHugo was refering to in the OP comment. From your code my guess is that you're using 'tyre physics' and inducing motive force from tyre torque/road friction. The torque on the carRigidBody is pointless for your stated goal. You need to either:
Add physics materials (and colliders) to your car tyres and terrain surfaces in order to facilitate 'friction' so that your torque will induce motive force.
Use AddForce on your wheels (or car) to apply a direct linear force to the body.
Upon re-reading your question... have you checked your keybindings, and does the "arrow up" that you're pressing actually affect the "Horizontal" axis?
The maximum angular speed of your project might be too low to provide actual movement.
Try changing it in the settings by going to:
Edit > Project Settings > Physics > Default Max Angular Speed
Change that value to something higher
I understand what you are trying to do by applying torque to the wheels but applying torque to the car itself may cause some weird behaviour
try removing the following line if you still have issues
carRigidbody.AddTorque(movement * carTorque * Time.fixedDeltaTime);
I am seeing a camera stutter when using smooth follow to lerp after my player with my camera in my multiplayer browser game. The player position is received from the server, the player lerps to that position, and my goal is for the camera to smoothly follow the player with its own, extra smoothing.
You can find my game at http://orn.io to see the current state, without smooth follow camera lerping, which is better but causes choppy movement and creates a headache. The current code for camera follow is:
void LateUpdate ()
{
if (Target == null) {
return;
}
currentScale = Mathf.Lerp(currentScale, -GameManager.TotalMass, Mathf.Clamp01 (Time.deltaTime * heightDamping));
Vector3 h = currentScale * 2f * Target.up;
Vector3 f = currentScale * 3f * Target.forward;
// tried lerping to this value but it causes choppy stutters
Vector3 wantedPosition = new Vector3(Target.position.x, Target.position.y, currentScale * 2) + h + f;
myTransform.position = wantedPosition;
myTransform.LookAt (Target, -Vector3.forward); // world up
}
and I have tried for days to tinker with the values, use fixed timestamps, put the camera movement in FixedUpdate/Update, use MoveTowards, and other changes, but am still experiencing issues.
Part of my problem that that the player position changes mid lerp, which causes a stutter since the target position changes in the middle of the lerp. This causes the camera to jump/sutter due to the target position of the lerp being changed in the middle of the lerp, and shakes due to the LookAt.
I would appreciate it if anyone could suggest a way to improve the camera following code as it stands now.
Is there any particular reason you need to use the Mathf.Lerp function?
Unity has a function, Vector3.SmoothDamp that is specifically designed for movement lerping:
void FixedUpdate() {
// Code for your desired position
transform.position = Vector3.SmoothDamp(transform.position, wantedPosition, ref moveVelocity, dampTime);
}
The above will smoothly follow the player by giving the SmoothDamp method control of the velocity variable. This is assuming that you supply it with a ref to store the current velocity and the damp time.
You can also adjust the damp time to change how smooth your transition is. This function will also automatically account for player movement mid-lerp.
To clarify, quoting from the documentation, dampTime in the above is:
Approximately the time it will take to reach the target. A smaller value will reach the target faster.
Also consider using Quaternion.slerp to smoothly rotate between the two rotations.
I want to have some more acceleration control over my wheel, which is just a cylinder that gets torque added.
wheel.AddTorque(wheel.transform.up * throttle);
What I actually want is to let it accelerate very quickly but at a give speed this the acceleration should quickly fall off. Like curve that starts very steep. Is there any way I can influence this using the basic .Addtorque?
Currently, my wheel just accelerates quickly to maximum velocity. Adding drag to it slows it down but I don't have the desired control over it.
You just affect the angularVelocity property of the rigidbody directly. Just as you can affect the velocity property instead of using the .AddForce method.
Try this pseudo code
public float topSpeed;
public float decelRate;
protected bool slowDown = false;
public void Update()
{
float speed = wheel.angularVelocity.magnitude;
if (speed >= topSpeed) slowDown = true;
if (slowDown)
{
speed -= decelRate * Time.deltaTime;
wheel.angularVelocity = wheel.angularVelocity.normalized * speed;
}
}
Keep in mind that magnitude calls are expensive, due to a square root function inside, though in this case i didn't see another way around it so you should be fine. Also i am not slowing it down in a set direction which is important, because this way it will slow down no matter what direction it is rotating in, or what way it is orientated.
There seem to be a fair amount of questions similar to this but none seem to really answer. I have a gameobject that can jump on a click of a button and automatically keeps going right.
I need the right moving motion to be constant but it ends up building faster and faster over time. If I use Velocity instead of AddForce, the motion is constant. But when I mouse click to jump, it takes like 10 over seconds to reach back down to ground.
Can I please get assistance on how I can keep the automatic movement to the right constant and still able to jump and reach back to ground fast. The following is my code. Thank you.
Edit:
Desired result
Gameobject constantly moving same speed to the right. When I jump, gameobject jumps and comes back down to ground over a period of 0.5 secs.
Jump is expected to be like a smooth flow like a ball that jumps and comes back down smoothly.
Current result Using AddForce to move right
Gameobject starts to move right slowly and picks up speed over time getting faster and faster thus not able to keep constant same speed.
Current result Using Velocity to move right
Gameobject able to keep constant speed as wanted, but when I jump the Gameobject jumps and takes about 10 seconds to get back down to ground (It slowly glides back down).
public float jumpSpeed = 300;
public float maxSpeed = 15;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
rb.AddForce(Vector3.up * jumpSpeed);
}
}
void FixedUpdate()
{
rb.AddForce(Vector3.right * maxSpeed);
}
//Trying to change velocity instead - Able to keep constant speed but when I jump, takes about 10 secs to get back down to ground.
public float jumpSpeed = 2000;
public float maxSpeed = 5;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
rb.AddForce(Vector3.up * jumpSpeed);
}
}
void FixedUpdate()
{
rb.velocity = new Vector2(5, 0);
}
I think there are a few points of confusion here, so I'll answer some clarifying questions of my own.
Why does the speed of the object increase without bound when using add force?
The AddForce command will increase the velocity of the object every time you apply it. In the code, this means every call to FixedUpdate is increasing the velocity.
I think the misunderstanding is related to this line of code in your Start method:
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
Vector2.ClampMagnitude is not persistent. That is to say, it does not clamp the magnitude going forward. What you probably meant was to prevent the velocity from ever breaking "maxSpeed" in which case you should call the clamp method in FixedUpdate.
However, this would have a different effect which you might not intend. When the game object is moving along only one axis, the entire magnitude of the velocity is along that axis. Once the game object begins moving along a second axis, for instance while jumping, the magnitude of the velocity is split across both. This means that while your game object is jumping (has a y component to its velocity) its horizontal speed (the x component of its velocity) would be diminished. In other words, jumping would slow down your game object's movement to the right.
Why does my object "float" slowly downwards when setting the velocity directly?
One of the advantages of using AddForce is that it modifies the targeted axis of a vector without modifying the others. Setting the velocity directly is a little more tricky because you may accidentally clobber the velocity changes caused by physics.
For instance, in your FixedUpdate code:
rb.velocity = new Vector2(5, 0);
is setting the x velocity of your object to 5 - creating the smooth horizontal movement you want - but at the same time, setting the y velocity to 0.
This is why you needed to crank your jumpSpeed up to 2000 to see any effect on the object's height: it only has a split second to move upwards before the FixedUpdate method resets its upward motion to 0. This is also why your object appears to be "floating" back to earth. The internal physics engine is trying to apply gravity to the object but is being foiled by your code which constantly resets the objects downward velocity.
One Other Comment
I noticed you had some code in your Update method that was acting on the object's physics - that is your jump code. A good rule of thumb is to keep all the code working on an object's physics in the FixedUpdate method, since this is called just before the physics engine does it's work while the Update method is called just before the rendering engine does its work to draw the game.
One Possible Solution
The AddForce technique is normally recommended when working on an object's velocity because it creates natural looking physics through acceleration. Setting an objects velocity directly can create strange looking effects because objects in reality don't work this way. For instance, imagine what it would look like to see a car change from 0mph to 60mph in less than a split second.
If you check Unity's documentation on Rigidbody.velocity, you'll see they make this same recommendation, but add that jumping may be a scenario where you want to break this rule. However, as I mentioned earlier, we need to be careful when setting the y velocity explicitly so as to avoid changing the object's speed along other axes.
public float jumpSpeed = 2;
public float maxSpeed = 1;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
var newVelocity = rb.velocity;
if (Input.GetMouseButtonDown (0))
newVelocity.y = jumpSpeed;
newVelocity.x = maxSpeed;
rb.velocity = newVelocity;
}