Bluebean
Bluebean

Reputation: 27

Bullet movement not working in Unity NetCode

Introduction: Basically I've been working with Unity Netcode. I got a relay server set up. A lobby system. Basic Movement down. Now I want to spawn a bullet that shoots the direction that the player is facing.

The Problem: After instantiating the bullet, setting its position and rotation, and spawning it in the network manager. The bullet going transform.forward doesn't go in the direction that the player is facing. It goes of in a random direction. Sometimes even going where the player is facing.

This is annoying, confusing, and it hurts my brain.

What I tried: I've tried changing the spawn position and rotation to the camera, the gun, and the player object. None worked. I printed the rotation and position: both matched the spawn point/rotation.

The basic structure of my heirarchy is such:Hierarchy

The code for the Bullet spawner:

    using UnityEngine;
    using Unity.Netcode;
    using Unity.Mathematics;
    public class Player_Shooting : NetworkBehaviour
    { 
        public GameObject bullet;
        public Transform gun;
        public Transform capsule;
    
        void Update()
        {
        if(GetComponentInParent<NetworkObject>().IsOwner)
        if(Input.GetMouseButtonUp(0))
            Shoot_Rpc();
        [Rpc(SendTo.Server)]
        public void Shoot_Rpc()
        {
            var instance =     Instantiate(bullet,capsule.transform.position,capsule.transform.rotation );
            var instanceNetworkObj = instance.GetComponent<NetworkObject>();
            instanceNetworkObj.Spawn();
        }   
    }

The Players Inspector: Player Inspector

The Bullets Code:

    public float speed;
    void Update()
    {
        print(transform.forward);
        if(NetworkManager.Singleton.IsServer)
        {
            transform.Translate(transform.forward * speed);
        }
    }

The Bullets Inspector: Bullet Inspector

Upvotes: 0

Views: 157

Answers (1)

Bluebean
Bluebean

Reputation: 27

I solved this by adding a forward vector 3 field in the bullet. When spawning the bullet I set the forward vector 3 to that of the main camera transform.forward. Then accelerated the bullet forward by the forward vector3. Still strange that the transform.forward of the bullet is bugged.

Upvotes: 0

Related Questions