Why does my car not move forward when pressing on keyboard? - c#

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

Related

How Can I Gradually Add More Force To An Object To Increase It's Speed Regardless of It's Direction?

I'm new in Unity. I am trying to make a 2D game similar to Pong. However, I want to increase more speed to Ball over time to make it harder. I set the gravity scale of the Ball to zero so that it doesn't fall down.
I added a force and bouncy Physics element to the ball. So it bounces back from walls and it goes to different directions.
Here is a screenshot of Game I'm working on:
MY QUESTION IS:
How can I add more force to the ball regardless of which direction it
bounces back?
<Note: I tried putting it inside FixedUpdate () method but the ball goes crazy because of constantly executing same function every frame. I was thinking of adding more force to the ball over time by using InvokeRepeating ( ) method later on to set time interval. If there is better idea of using other techniques, giving me a little advice will help me a lot>
Thank you !
I would recommend using a Coroutine or an InvokeRepeating. I would also recommend changing your code a bit.
rbBall.AddForce(rbBall.transform.right * ballForce)
The above snippet will add the ballForce in the direction the rbBall is moving.
Now for the two example snippets.
Coroutine
private float timeBeforeAddForce = 5f;
private void Start()
{
StartCoroutine(GradualAddForceToBall());
}
private IEnumerator GradualAddForceToBall()
{
// wait for 5 seconds
yield return new WaitForSeconds(timeBeforeAddForce);
// add the speed
rbBall.AddForce(rbBall.transform.right * ballForce)
// call the coroutine again
StartCoroutine(GradualAddForceToBall());
}
InvokeRepeating
private void Start()
{
InvokeRepeating("GradualAddForceToBall", 0.0f, timeBeforeAddForce);
}
private void GradualAddForceToBall()
{
rbBall.AddForce(rbBall.transform.right * ballForce)
}
If you want to change the current time of how long the speed is applied, I would go with the Coroutine as you can gradually decrease the timeBeforeAddingForce every time it enters the Coroutine.
I found the answer. You can force an object to be a specific speed while keeping its same movement direction - normalize the velocity (which sets the value to have a mangitude of 1) and then multiply it by your desired speed:
Here is the code:
public float currentSpeed = 5f;
void FixedUpdate()
{
//This will let you adjust the speed of ball using normalization
rbBall.velocity = rbBall.velocity.normalized * currentSpeed;
}
Adjust the currentSpeed variable to change it's speed.
""

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.

Unity2D: implementing a running effect to my character

I'm trying to achieve the same effect done Knuckles does in the new game Sonic mania, the effect can be seen here (2:18 - 2:25). So far I duplicated my main player and lowered the duplicated players alpha so that it looks a bit transparent, I also added the script below on the duplicated player to give the duplicated player some distance to the original player; however I wasn't quite sure how I can make the duplicated players slowly return the original player when the player isn't moving! I attempt using animation but it didn't look as good as what was shown in the video, I also tired to shorten the distance over Time.deltaTime however it still didn't look effective! Is there a better way of attempting the same effect shown in the video?? Thank you :)
public GameObject Player;
public float distance = 0.75f;
// Use this for initialization
void Start () {
distance = 0.42f;
}
// Update is called once per frame
void Update () {
transform.position = (transform.position - Player.transform.position).normalized * distance + Player.transform.position;
}
You can try using TrailRenderer.
Here's the documentation: https://docs.unity3d.com/Manual/class-TrailRenderer.html
You can activate it during the run effect and deactivate it otherwise.

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