Рейкаст не поражает врагаC#

Место общения программистов C#
Ответить
Anonymous
 Рейкаст не поражает врага

Сообщение Anonymous »

Я пытаюсь создать сценарий атаки игрока, чтобы при щелчке мышью по врагу в определенном диапазоне вызывалась функция атаки врага (которая затем вызывает функцию получения урона из сценария врага. Однако когда я нажимаю кнопку воспроизведения и нажимаю на врага (у которого достаточно большой коллайдер, чтобы его можно было обнаружить с помощью рейкаста, и который находится в пределах диапазона атаки), он не получит урона.

Код: Выделить всё

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

public class PlayerAttack : MonoBehaviour
{
public int attackDamage = 10;
public float attackRange = 1.5f;
public LayerMask enemyLayer;

public CinemachineVirtualCamera virtualCamera;
private Camera cameraComponent;
private CinemachineRecomposer recomposer;
private Vector3 cameraOffset; // Variable to store the camera offset

void Start()
{
cameraComponent = virtualCamera.GetComponentInChildren();
recomposer = virtualCamera.GetComponent();
var cameraOffsetComponent = virtualCamera.GetComponent();

if (cameraComponent == null)
{
Debug.LogError("Camera component not found on the virtual camera.");
}
if (recomposer == null)
{
Debug.LogError("CinemachineRecomposer component not found on the virtual camera.");
}
if (cameraOffsetComponent != null)
{
// Set the camera offset values
cameraOffsetComponent.m_Offset.y = 7.67f;
cameraOffsetComponent.m_Offset.z = -0.14f;
// Store the offset in the cameraOffset variable
cameraOffset = cameraOffsetComponent.m_Offset;
}
else
{
Debug.LogError("CinemachineCameraOffset component not found on the virtual camera.");
}
}

void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Set the tilt angle of the Cinemachine recomposer
recomposer.m_Tilt = 31; // Assuming m_Tilt is the correct property name
Vector3 cameraPositionWithOffset = cameraComponent.transform.position + cameraOffset;

Ray ray = cameraComponent.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * 30, Color.green, 5f);

if (Physics.Raycast(ray, out hit, attackRange, enemyLayer))
{
Debug.Log("Raycast hit: " + hit.collider.name);
AttackEnemy(hit.transform);
}
else
{
Debug.Log("Raycast did not hit");
}
}
}

void AttackEnemy(Transform enemy)
{
EnemyHealth enemyHealth = enemy.GetComponent();
if (enemyHealth != null)
{
enemyHealth.TakeDamage(attackDamage);
Debug.Log("Attacked the enemy with the mouse button!");
}
}

void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
введите здесь описание изображения
введите здесь описание изображения
В какой-то момент я подумал, что, возможно, дело в ракурсе камеры, но я могу ясно увидеть, как луч рисуется и проходит через коллайдер противника. Пожалуйста помоги! У меня болит мозг.

Подробнее здесь: https://stackoverflow.com/questions/784 ... ting-enemy
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»