I want to make my character jump by drawing lines.
But while my code is going towards the x-axis direction in 2D, when I switch to 3D, it always turns upwards regardless of the direction of the line. There is no change in the X-axis. My code is as follows:
if (other.gameObject.CompareTag("Line"))
{
rb.AddForce(Vector3.up * speed * Time.deltaTime, ForceMode.Impulse);
/ / Destroy(other.gameObject);
}
Could someone suggest how to correct my code?
CodePudding user response:
Currently you're passing in Vector3.up as the force's direction, meaning that the character will always jump straight up.
If you want the character to jump in the line's direction, maybe try using the line's transform to send the player the right way, like this:
if (other.gameObject.CompareTag("Line"))
{
Vector3 jumpDir = other.gameObject.transform.up;
rb.AddForce(jumpDir * speed * Time.deltaTime, ForceMode.Impulse);
}
Now you'd need to point the "Line" GameObject in the direction you want the player to jump when they collide. (In the scene view, the Line transform's green arrow should be the character's jump direction) You could switch it to the red or blue arrows (x or z axes) with
jumpDir = other.gameObject.transform.right;
or
jumpDir = other.gameObject.transform.forward;
respectively.
CodePudding user response:
You need to get the direction depending on the line you drew. Depending on how you implemented your lines, you can get the directions from the transform via
Transform.up
Transform.forward
Transform.right
If you need the other directions, you can simply invert the Vectors.
Also you don't need to use Time.deltaTime while using rb.AddForce(), because the physic-system is taking care of it.