问题描述
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileBehavIoUr : MonoBehavIoUr
{
#region Variables
[Serializefield] private int _veLocity;
private int _directionx = 1;
private int _directiony;
private bool _isHit;
private Rigidbody2D rb;
public int VeLocity { get => _veLocity; set => _veLocity = value; }
public bool IsHit { get => _isHit; set => _isHit = value; }
public int Directionx { get => _directionx; set => _directionx = value; }
public int Directiony { get => _directiony; set => _directiony = value; }
#endregion
#region Game Loop
void Awake()
{
Setup();
}
private void Update()
{
}
void FixedUpdate()
{
MoveProjectile();
Debug.Log(_directionx);
}
#endregion
#region Helper Functions
private void MoveProjectile() => transform.position += (-transform.right * (Time.deltaTime * VeLocity)) * Directionx;
private void Setup()
{
rb = GetComponent<Rigidbody2D>();
IsHit = false;
}
#endregion
}
这个类描述了我想在场景开始时射击的射弹的行为。属性 DirectionX 负责抛射物的运动方向。因此,如果 Directionx = 1,则弹丸应向左移动,如果 Directionx = -1,则弹丸应向右移动。现在我想通过另一个类来改变_directionx。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollision : MonoBehavIoUr
{
public ProjectileBehavIoUr projectileBehavIoUr;
void Start()
{
}
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Projectile")) { ReflectProjectile(); }
}
private void ReflectProjectile()
{
projectileBehavIoUr.Directionx = -1;
Debug.Log(projectileBehavIoUr.Directionx);
}
}
这个类负责物体与玩家的碰撞。现在,如果带有“Projectile”标签的 Projectile 击中玩家,则 directionx 属性设置为 -1,效果很好。但有个问题: Console Log 即使 directionx 暂时设置为 -1,它也会变回 1。因此,射弹不会被反射并飞过玩家。
感谢您的阅读,非常感谢您的帮助!
解决方法
如果您有多个投射物实例,您可能会在控制台中获得另一个投射物固定更新的 1 个方向:
void FixedUpdate()
{
MoveProjectile();
Debug.Log(_directionx);
}
您可以检查区分您的日志消息