Home > Software design >  Unity prevent players from colliding with each other
Unity prevent players from colliding with each other

Time:08-25

I'm building a 2D multiplayer game with Unity and Photon and I'm currently facing a problem where my players are colliding with each other and I don't want this behavior to happen...

I'm using the Unity enter image description here

And that's my PlayerController script:

void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info){
        if(stream.isWriting){
            stream.SendNext(transform.position);
            stream.SendNext(localPlayerName.text);
        } else{
            targetPosition = (Vector3)stream.ReceiveNext();
            remotePlayerName.SetText((string)stream.ReceiveNext());
        }
    }

private void FixedUpdate()
    {
        if(PhotonView.isMine){
            if(movementInput != Vector2.zero){
                int count = gameObject.GetComponent<Rigidbody2D>().Cast(
                    movementInput,
                    movementFilter,
                    castCollisions,
                    moveSpeed * Time.fixedDeltaTime   collisionOffset
                );

                if(count == 0){
                    transform.position  = (Vector3)movementInput * moveSpeed * Time.fixedDeltaTime;                
                }
            }
        } else {
            moveOtherPlayer();
        }
    }

private void moveOtherPlayer() {
        transform.position = Vector3.Lerp(transform.position, targetPosition, 0.25f);
    }

void OnMove(InputValue movementValue){
        this.movementInput = movementValue.Get<Vector2>();
    }

how can I avoid the collision between the 2 player instances ?

CodePudding user response:

Good day!

You could try turning off object collisions in the layer collision matrix. You can find the matrix in: Edit > Project Settings and in the Physics tab. How it works is:

  1. You assign your GameObjects (your players) to a layer in the top-right.
  2. Go the the matrix and where the layer columns and rows meet, there will be a tickbox.
  3. If you turn off that tickbox, then it means that GameObjects with those layers will ignore collisions with eachother. Triggers will also ignore eachother.

I hope this helps and good luck in your project!

  • Related