Home > Net >  Unity: When my Player touches another object it gets a wierd constant pushback motion
Unity: When my Player touches another object it gets a wierd constant pushback motion

Time:11-07

I have a weird problem and cant seem to fix it

i was creating my first game in unity and i was testing around a bit after creating a movement system and whenever i touch another object (it doesnt matter if it has a rigidbody or not) my player suddenly starts moving on its own.

i have a video showing what exactly happens: https://youtu.be/WGrJ0KNYSr4

i have tried a few different things already and i determined that it has to do something with the physics engine because it only happens when the player isnt kinematic, so i tried to increase the solver iterations for physics in the project settings but the bug was still happening so i looked for answers on the internet yet the only thing i found was to remove Time.deltaTime tho it still didnt work. I have found that it seems to happen less though when the player is moving fast.

i would really appreciate if somebody could help me with this since its my first real game and im creating it for the Seajam thats happening on itch.io.

here is the code for my playercontroller script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
public float playerSpeed = 3f;
private Rigidbody playerRb;
public GameObject cameraRotation;
// Start is called before the first frame update
void Start()
{
    playerRb = GetComponent<Rigidbody>();
}
float verticalSpeed;
float horizontalSpeed;
bool isOnGround = true;

// Update is called once per frame
void Update()
{
    //get controlled forward and backward motion
    verticalSpeed = Input.GetAxis("Vertical");
    transform.Translate(Vector3.forward * playerSpeed * verticalSpeed * Time.deltaTime);

    //get controlled sidewards motion
    horizontalSpeed = Input.GetAxis("Horizontal");
    transform.Translate(Vector3.right * playerSpeed * horizontalSpeed * Time.deltaTime);

    //lock the rotation of the player on the z and x axis
    transform.eulerAngles = new Vector3(0, cameraRotation.transform.eulerAngles.y, 0);

    //when pressing space jump and prevent air jump
    if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
    {
        playerRb.AddForce(Vector3.up * 10, ForceMode.Impulse);
        isOnGround = false;
    }
}
//check if the player is on the ground
private void OnCollisionEnter(Collision collision)
{
    isOnGround = true;
}

}

CodePudding user response:

Try not locking the player's rotation by script, maybe it is causing the problem due to gimbal lock. Instead go to your player's RigidBody->Constraints and then lock it. You can read more about it here https://fr.wikipedia.org/wiki/Blocage_de_cardan

  • Related