单击按钮时,我调用 Shoot () 函数,它应该在角色的位置创建一颗子弹,但在场景的中心创建。
在 PlayerShooter 代码中的 Start() 处,我检查它是否返回正确的 trasform.position 值,但是当在 Shoot () 函数中按下按钮时它返回 0,0,0
我发现子弹是在预制件的位置上产生的,而不是在预制件位置的实例化对象上,我该如何解决这个问题?
拍摄代码:
using Photon.Pun;
using UnityEngine;
public class PlayerShooter : MonoBehaviour
{
[SerializeField] private GameObject _bullet;
[SerializeField] private float _distanceMultiplier;
public void Shoot()
{
if (PhotonNetwork.PlayerList.Length > 1)
{
PhotonNetwork.Instantiate(_bullet.name, transform.position, transform.rotation);
}
}
}
角色移动脚本:
using UnityEngine;
using Photon.Pun;
[RequireComponent(typeof(Rigidbody2D), typeof(CapsuleCollider2D))]
public class PlayerMover : MonoBehaviour
{
[SerializeField] private float _speepMoving, _speedRotation;
private Rigidbody2D _rigidbody;
private Vector2 _direction;
private PhotonView _view;
[HideInInspector] public FixedJoystick joystick;
private void Start()
{
_view = GetComponent<PhotonView>();
_rigidbody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (_view.IsMine && PhotonNetwork.PlayerList.Length > 1)
{
_rigidbody.velocity = new Vector2(joystick.Horizontal * _speepMoving, joystick.Vertical * _speepMoving);
RotatePlayer();
}
}
private void RotatePlayer()
{
_direction = new Vector2(joystick.Horizontal, joystick.Vertical);
if (_direction != Vector2.zero)
{
Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, _direction);
_rigidbody.MoveRotation(Quaternion.Lerp(transform.rotation, toRotation, _speedRotation * Time.deltaTime));
}
}
}
我已经用这段代码完成了:
using Photon.Pun;
using UnityEngine;
using UnityEngine.UI;
public class PlayerShooter : MonoBehaviour
{
[SerializeField] private GameObject _bullet;
[SerializeField] private float _distanceMultiplier;
[HideInInspector] public Button shootButton;
private void Start()
{
shootButton.onClick.AddListener(delegate () { Shoot(); });
}
public void Shoot()
{
if (PhotonNetwork.PlayerList.Length > 1)
{
PhotonNetwork.Instantiate(_bullet.name, transform.position + transform.up * _distanceMultiplier, transform.rotation);
}
}
}