Hi guys im making a open world game and i used unitys terrain object to create a large terrain and mass place some trees and grass but now that i have a axe which i modeled in Blender and a swinging animation for when you press LMB i want to destroy the trees when the swing anim hits it I’m having some trouble getting the axe to know wether it’s hitting the tree or the terrain?
heres a few of my scripts
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tree : MonoBehaviour
{
public void DestroyTree()
{
Debug.Log("Tree destroyed!");
// Add any particle effects, sounds, or animations for destruction if needed
Destroy(gameObject); // Destroy the tree object
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Axe : MonoBehaviour
{
private Animator animator;
private bool isSwinging = false;
public LayerMask treeLayer; // LayerMask to specify which layers we want to detect
public float swingDistance = 2f; // Adjust this based on how far you want the axe to swing
void Start()
{
animator = GetComponent<Animator>();
}
void Update()
{
// Trigger swing animation on LMB press
if (Input.GetMouseButtonDown(0)) // Left Mouse Button
{
SwingAxe();
}
}
private void SwingAxe()
{
if (!isSwinging)
{
isSwinging = true;
Debug.Log("Swinging axe!"); // Ensure swing is triggered
animator.SetTrigger("Swing"); // Trigger the swing animation
}
else
{
Debug.Log("Already swinging..."); // Debug to ensure this isn't being skipped
}
// Raycast to detect if axe hits tree during swing
RaycastHit hit;
Vector3 swingDirection = transform.forward; // Axis along which the axe swings
if (Physics.Raycast(transform.position, swingDirection, out hit, swingDistance, treeLayer))
{
Debug.Log("Axe hit a tree!");
// Assuming the tree is in the treeLayer and has a Tree script
Tree tree = hit.collider.GetComponent<Tree>();
if (tree != null)
{
tree.DestroyTree(); // Destroy tree on hit
}
}
}
}
this is my first time using raycast so i dont know if this is right
any help would be greatly appreciated.