- Home /
How to set the velocity in Z direction to 0?
Hi, i just made my first game using Unity which was a lot of fun X). Because i'm really new to C# I really have no idea how to code by myself and needed some help.
So this is the script that im using for my player movement:
using UnityEngine;
public class Playermovement : MonoBehaviour {
// Use this for initialization
public Rigidbody rb;
public float forwardForce = 2000f;
public float SidewaysForce = 500f;
//awodhbfa
//lzcnvl;kmfsd
void FixedUpdate ()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if ( Input.GetKey("d"))
{
rb.AddForce(SidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange );
}
if (Input.GetKey("a"))
{
rb.AddForce(-SidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
but when i go and play the game, the movement feels really sloppy and you feel like a drunk man getting forces of 100f in Z direction xd. So what i was hoping that i could do was to add an if statement saying that if im not clicking A or D, set my speed in Z direction to 0. Does anyone know if this is possible?
Answer by maxoja · Sep 13, 2018 at 11:49 AM
this snippet will help you to make your z-axis velocity becomes 0 when both A and D are not pressed
if(!Input.GetKey("a") && !Input.GetKey("d")) {
Vector3 resultVelocity = rb.velocity;
resultVelocity.z = 0;
rb.velocity = resultVelocity;
}
Your answer
Follow this Question
Related Questions
2d Platformer Horizontal Max Speed 2 Answers
Apply same amount of force even after gameObjects are fixed joint 0 Answers
Insure that the player can't increase speed when over the speed limit 3 Answers
How can you instantiate a prefab with an initial burst of speed using ForceMode2D.Impulse? 2 Answers
Ball Addforce Acceleration Speed 1 Answer