Jumping increases movement speed - c#

I'm making a game with ball physics and an FPS camera. I have this bug where the player's movement is increased when I jump.
Example:
Running along the Z axis on a plane:
Suddenly jumping:
My code:
void Update()
{
// Input
moveFwrd = Input.GetAxis("Horizontal");
moveSide = Input.GetAxis("Vertical");
// Player Jump
if (Input.GetKeyDown(jumpKey) && Physics.Raycast(
transform.position,
Vector3.down,
DistanceToTheGround + 0.1f))
{
rb.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
}
// Braking
if (Input.GetKey(brakeKey))
{
rb.angularDrag = brakeForce;
}
else
{
rb.angularDrag = 0.01f;
}
}
void FixedUpdate()
{
// Player Movement
Vector3 movement = cam.transform.right * moveFwrd +
cam.transform.forward * moveSide;
movement = movement.normalized;
rb.AddForce(movement * speed);
}
}

Most likely, the answer is friction. Depending on the physics material used for the player's Rigidbody collider and the physics material used for the floor, the Rigidbody will behave differently:
Static friction describes the friction when both objects are not moving (i.e. before the player starts moving), dynamic/kinetic/sliding friction describes the friction when the player is moving along/on the floor. It will also determine if the rigidbody slides or rolls on the floor, you could experiment with different physics materials to see the effects.
The reason why you see faster movement in mid-air in forward direction after pressing the jump button is that the Rigidbody is no longer affected by "contact friction" between solid materials while airborne, hence it will move faster with the same applied forward force. - However, there's still friction involved: air resistance; which can be controlled by Rigidbody.drag and Rigidbody.angularDrag.
If you want to get rid of this simulated bahavior, you could do various things: Use different physics materials, Rigidbody.drag, Rigidbody.mass values, or try to experiment with a different ForceMode like ForceMode.VelocityChange arguments in Rigidbody.AddForce(). Or do not use the physics engine and rigidbodies at all for motion (colliders and raycasts can still be used).
Side notes:
FixedUpdate() is called at regular intervals, and is the recommended place to do physics related scripting. It is actually called at the same frequency as the internal physics engine is updated, like documented here. The duration between every call is constant: Time.fixedDeltaTime.
Update() on the other hand is called at a variable rate, and has a variable duration Time.deltaTime, which results in different frame rates (FPS). This method can be used for the visual rendering or state processing of the game, and should not be used to update physics related stuff if possible.
In the script above, you use Rigidbody.AddForce() in both methods Update() and FixedUpdate(). In the latter with the default argument ForceMode.Force and in the other case with ForceMode.Impulse. In both cases you do not take the frame time into account, which is fine in the case of an impulse, applied once (after a key has been pressed). In the other case the direction vector gets normalized, so it isn't really a problem either, because the method is called at a fixed rate... but it could be written a bit more clearly.

Related

AddForce works strangely

I'm making a game: side view basketball in Unity3D. I want the script to calculate the force of impact on the ball at which the ball will reach the basket based on the value of the distance from the ball to the basket. But I don’t know how to write it correctly, so I edit the impact force manually. There is also the problem that when the ball hits, in the first two frames the ball travels a much greater distance than in the rest. The Shoot method is called in Update if the ball is in the bot's collision zone. Ball hit code and screenshots (Sequence of screenshots: 1-frame before hit, 2-first frame after hit, 3-second frame after hit, 4-3rd frame after hit):
private void Shoot{
var heading = pointTarget.position - go_ball.transform.position;
var distance = heading.normalized;
var distancemag = heading.magnitude;
go_ball.GetComponent<Rigidbody>().AddForce(distance * distancemag * UpForce * Time.deltaTime, ForceMode.VelocityChange);
go_ball.GetComponent<Rigidbody>().AddForce(distance * distancemag * LeftForce * Time.deltaTime, ForceMode.VelocityChange);}
I also adjust MaxVelocity in a separate ball script method(idk maybe problem hides here)
if (rb_ball.velocity.magnitude > MaxVelocity)
{
rb_ball.velocity = Vector3.ClampMagnitude(rb_ball.velocity, MaxVelocity);
}
As you can see the difference in the distance from the ball in the first two frames is different. What could be the problem?

Why doesn't the object bounce correctly at lower speeds in Unity 2D?

P.S. I have already seen this question asked here, but this applies to Unity 3D, whereas I am working in Unity 2D.
My main issue is that a ball in my Unity 2D game doesn't bounce correctly when the speed is set to a lower value but works fine at faster velocities. Note that I have already tried to change the bounce threshold in Project Settings, but it does not do anything to solve my issue. I have applied a Rigidbody2D component, BoxCollider2D, and a Physics Material 2D that is supposed to make the ball bouncy.
Here are some of my current settings (if that helps):
Rigidbody2D Settings:
Body Type: Dynamic
Material: Bouncy (name of my physics material)
Simulated: True
Use Auto Mass: False
Mass: 1
Linear Drag: 0
Angular Drag: 0
Gravity Scale: 0
Collision Detection: Discrete
Sleeping Mode: Start Awake
Interpolate: None
Physics Material 2D Settings:
Friction: 0
Bounciness: 1
Here is some of the initialization code that runs when the game loads to start the movement of the ball:
float x = Random.value < 0.5f ? -0.75f : 0.75f;
float y = Random.value < 0.5f ? Random.Range(-0.75f, -0.5f) : Random.Range(0.5f, 0.75f);
Vector2 direction = new Vector2(x, y);
rb.AddForce(direction * speed);
Note: This code is inside a custom class (inherits MonoBehavior) I made for the ball object to manage the physics actions.
For additional information, refer to this video to see how the game responds.
The slower speed for the ball is necessary for my game, and I would really appreciate it if I could get some help on this issue.
The Unity physics system is non-deterministic and does not make promises of conservation of energy, or other features. if you want to fine-tune your physics system to such a degree you may want to consider using other means of controlling the ball's velocity.
But if you do want to continue using the built-in physics engine anyway, you could consider using faster velocities and lowering the timescale to compensate.
For example:
float x = Random.value < 0.5f ? -3f : 3f;
float y = Random.value < 0.5f ? Random.Range(-3f, -2f) : Random.Range(2f, 3f);
and somewhere in Start or Awake
Time.timeScale = 0.25f;
and you'll probably want to increase the velocities of your paddles as well to compensate for the timescale change.
Another option is using faster velocities and increasing the size of everything and making the camera view larger to make everything appear the same size. Requires fewer code changes but potentially many more scene/component changes.

How can i use rigidbody2d.velocity to follow an object in Unity?

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

Raycast, in Unity 3d does not detect all obstacles

I'm trying to make a very simple race game with spheres, however, I face many problems.
First of all, I'm trying to make a very simple AI system for opponents.
The problem I have here is that I want opponents to detect obstacles and avoid them using Raycast but only a certain type of obstacle , a simple cube is detected.
I've created a simple sphere as opponent and wrote a script so it can move and detect obstacles
Here is update function:
void FixedUpdate()
{
transform.Translate(Vector3.forward * Time.deltaTime * speed);
if (Physics.Raycast(transform.position, transform.forward, 100.0f))
print("There is something in front of the object!");
}
The message is printed only when there is a cube forward and it does not detect any other obstacles. What can be so wrong? Also, is there any idea how to move left or right when opponent raycast an obstacle?
obstacle that is detected
hierarchy
cube01 that is child of obstacle2 that is not detected
Only collider components are detected using raycast, make sure you have an appropriate collider (size of the collider does not necesarily match size of the mesh that gets rendered). Normally also layers on which objects are are important but syntax you are using is not checking for layer mask anyway
Unity Physics Best Practices (As in https://unity3d.com/pt/learn/tutorials/topics/physics/physics-best-practices) recommends that we don't use Raycasts in FixedUpdate, as it is heavy to process and may not always work.
There is also some tips about Matrix Layers that will help you improve performance and avoid such bugs.
Good luck!
You can use Debug.DrawLine() or Debug.DrawLine() to debug the line and see if it cross the obstacles or not.
Here is the documentation for them
DrawRay
DrawLine
For moving right and left I think you can add something like this
void FixedUpdate()
{
Vector3 dir = Vector3.forward * Time.deltaTime * speed;
if (Physics.Raycast(transform.position, transform.forward, 100.0f))
{
print("There is something in front of the object!");
dir += Vector3.Right * horizontalSpeed * Time.deltaTime;
}
}
You might also consider ray casting two rays to detect the direction to lean to if it will be the left or the right.

Constant speed for Adding Force without affecting jump

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;
}

Categories

Resources