Jump to content

Moving script bugging when rigidbody is added Unity

Spudwell06

I have been making my first Unity C# game and still getting used to it

the y axis keeps resetting every time I move

I think the line below is the issue, but u dont know what to change the 'y' to:

Vector3 direction = new Vector3(horizontal, 0fvertical);
 
Im still new to coding in C# and it is really maddening 
Link to comment
Share on other sites

Link to post
Share on other sites

That's very little context to go on. The only line you've shown in the initialization of a new Vector3 instance. Where does this call occur? What do you do with the vector after it has been initialized? If you create a new instance every time you move it would explain why things keep resetting, but without the actual code there's no way to tell.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

I agree with @Eigenvektoron this. Definitely need more context on this one. I would post up your entire movement script so that we can actually figure out whats wrong and not simply guess at what the issue is. 

 

In case you've never dealt with game math before see below. 

 

Here's an excellent primer for coordinate systems, Linear Algebra and Vector mathematics. A lot of the time when you're programming you don't need to understand the math you just have to understand how to implement it, but with anything game, graphics or physics related you have to know the math.  https://www.youtube.com/channel/UCEhBM2x5MG9-e_JSOzU068w

 

The code makes a lot more sense once you understand how you actually represent translations, rotations and scaling. 

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to comment
Share on other sites

Link to post
Share on other sites

28 minutes ago, trag1c said:

I agree with @Eigenvektoron this. Definitely need more context on this one. I would post up your entire movement script so that we can actually figure out whats wrong and not simply guess at what the issue is. 

 

In case you've never dealt with game math before see below. 

 

Here's an excellent primer for coordinate systems, Linear Algebra and Vector mathematics. A lot of the time when you're programming you don't need to understand the math you just have to understand how to implement it, but with anything game, graphics or physics related you have to know the math.  https://www.youtube.com/channel/UCEhBM2x5MG9-e_JSOzU068w

 

The code makes a lot more sense once you understand how you actually represent translations, rotations and scaling. 

My Entire code, i tried fixing it (it did not work)

It is a logic error not a syntax because it runs

Im using Rigidbody and Cinemachine

Sorry for the bulky code

 

public class NewBehaviourScript : MonoBehaviour
{
    [SerializeFieldprivate Transform groundCheckTransform = null;
    [SerializeFieldprivate LayerMask playerMask;
    private bool jumpKeyWasPressed;
    private bool superJump;
    private Rigidbody RigidbodyComponent;
    private int superJumpsRemaining;
 
    public CharacterController controller;
    public Transform cam;
    public float speed = 6f;
    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;
 
    void Start()
    {
        RigidbodyComponent = GetComponent<Rigidbody>();
    }
 
     void Update()
    {
        //Check if space key is pressed down
        if (Input.GetKeyDown(KeyCode.Space)) 
        {
            jumpKeyWasPressed = true;
        }
        if (Input.GetKeyDown(KeyCode.LeftAlt)) 
        {
            if (superJumpsRemaining > 0)
            {
                superJump = true;
            }
        }
 
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal0fvertical).normalized;
 
        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.xdirection.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y,targetAngleref turnSmoothVelocityturnSmoothTime);
            transform.rotation = Quaternion.Euler(0fangle0f);
 
            Vector3 moveDir = Quaternion.Euler(0ftargetAngle0f) * Vector3.forward;
            controller.Move(RigidbodyComponent.velocity = moveDir.normalized * speed * Time.deltaTime);
 
            if(Physics.OverlapSphere(groundCheckTransform.position0.1fplayerMask).Length == 0)
            {
                return;
            }
        }
    }
    private void FixedUpdate()
    {
        if (jumpKeyWasPressed == true
        {
            RigidbodyComponent.AddForce(Vector3.up * 5ForceMode.VelocityChange);
            jumpKeyWasPressed = false;
        }
 
        if (superJump == true
        {
            RigidbodyComponent.AddForce(Vector3.up * 15ForceMode.VelocityChange);
            superJump = false;
            superJumpsRemaining--;
        }
    }
}
Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Spudwell06 said:

My Entire code, i tried fixing it (it did not work)

It is a logic error not a syntax because it runs

Im using Rigidbody and Cinemachine

Sorry for the bulky code

~Snip~

So some quick notes that hopped out to me as soon as I looked. Move the object using the character controller (CC) and not the rigid body (RB). Rigid body is great for when you want it to interact somehow with other things as a physics object, but trying to use it to navigate about the world is a nightmare to say the least. The other thing is you're trying to set the movement using BOTH the RB and the CC so you're going to get some really funky movement. Your move command should look exactly like this.

 

controller.Move(moveDir.normalized * speed * Time.deltaTime);

 

Onto the asked problem. Basically what is happening is that you're always setting the y component of the direction vector to zero so it never moves up or down.  So the y component of you direction vector should be set according to your branching but regardless of that every frame it should have a gravitational acceleration subtracted from it so that everything comes back to the ground.

 

So if you're performing a jump you add a value into y if you're not performing a jump you should subtract from y.

 

Some pseudo code below. (It should work once you adapt it to actual code but its completely untested and hastily thrown together.)

 

// Check if you're character is on the ground. e.g. solid object collider underneath it.
// Set the y component of the movement vector. This would be an accelleration so you it's multiplied against time. Since the script gets executed every // frame you have to use the delta time between frames.
//Assuming you have a collider underneath your player you shouldn't have any problems with it falling through the world.
Direction.y = someGravitationalConstant * Time.deltaTime;

if(controller.isGrounded())
{
        // Some jump mechanic
        if(key)
        {
        	Direction.y = someJumpValue;
        }
        
        // Movement stuff.
        float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
        float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y,targetAngle, ref turnSmoothVelocity, turnSmoothTime);
        transform.rotation = Quaternion.Euler(0f, angle, 0f);
 
        Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
        /// Stuff...   
}


controller.Move(moveDir.normalized * speed * Time.deltaTime);

 

 

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to comment
Share on other sites

Link to post
Share on other sites

5 hours ago, trag1c said:

Some pseudo code below. (It should work once you adapt it to actual code but its completely untested and hastily thrown together.

8 hours ago, Eigenvektor said:

That's very little context to go on

I'm so sorry but I just do not understand, I have tried

C# is so different to python and I cannot get my head around it

If you get the time, can you please go more in depth/idiot-proof a response

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×