- Home /
How do I stop a velocity only on the X axis?
I am making a character that moves in a 3D world with 2D mechanics. They slip and slide about using the code below. I want it so that when the player lets go of the A/D keys it quickly brings them to a stop on the X-axis. I don't want to use dampen on the Rigidbody because that will affect both Jumping and falling.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float forceMult = 100;
public float GravityMult = 0.5f; // Gravity
private Rigidbody rb; //Rigidbody
public bool JumpReady = true; //Jump only if on floor
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
//Movement
if (Input.GetKey(KeyCode.A))rb.AddForce(Vector3.left * forceMult);
if (Input.GetKey(KeyCode.D))rb.AddForce(Vector3.right * forceMult);
//Jump
if (Input.GetKey(KeyCode.W))rb.AddForce(Vector3.up * forceMult / 2);
if (Input.GetKeyDown(KeyCode.W) && JumpReady == true)
{
rb.AddForce(Vector3.up * forceMult * 24);
JumpReady = false;
}
//DashDown
if (Input.GetKey(KeyCode.S))rb.AddForce(Vector3.down * forceMult * 15);
//Movement End
if (Input.GetKeyUp(KeyCode.A))
{
//Quick Stop A
}
if (Input.GetKeyUp(KeyCode.D))
{
//Quick Stop D
}
//Gravity
rb.AddForce(Vector3.down * forceMult * GravityMult * 2);
}
}
Answer by EDevJogos · Jun 21, 2019 at 06:31 PM
Rigidbodys have a property velocity, see more about it here:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
You can assing a new velocity, Vector3, with the x coordinate = 0:
rb.velocity = new Vector3(0f, rb.velocity.y, rb.velocity.z);
This should do the trick.
rb.velocity = new Vector3(0f ,0f , 0f) * rb.velocity; I tried doing this but Unity says I can't multiply vector 3 by Vector 3. :P Could you tell me how?
I tried this as well but does not seem to be running. Vector3 V$$anonymous$$ult = new Vector3(0f,1f,1f); rb.velocity *= V$$anonymous$$ult;
Oh thats true, sorry, my bad, you can do: rb.velocity = new Vector3(0f, rb.velocity.y, rb.velocity.z);
Vou can also use Scale:
https://docs.unity3d.com/ScriptReference/Vector3.Scale.html
rb.velocity = Vector3.Scale(rb.velocity, new Vector3(0f, 1f, 1f));
Answer by ShamimAkhter · Jun 21, 2019 at 07:32 PM
You can use rigidbody constraints in the inspector under rigidbody component. There just check " Freeze Position X"
Also use FixedUpdate() rather then Update() for Applying forces.
Your answer
Follow this Question
Related Questions
Objects with colliders going through walls and each other. 3 Answers
Moving a CharacterController Object together with a RigidBody Object 1 Answer
C# DragRigidbody ArgumentException: get_main can only be called from the main thread 2 Answers
Convert Rigidbody code to CharacterController usable 0 Answers