Hi Guys! Apologies I still dont understand how this forums works with posting code. But ive attached a youtube video to hopefully explain what Im after.
I have a new issue. Ive tried to detach from a parent at the current cached location ThrowSword() method. that is called under update seems to work pretty well. However when I attempt to pickup the sword again it (btw does go where i place it the first time) but not where i go the second time it just goes back to the first cached location. Any pointers on this would be fantastic!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UIElements;
public class swordHandler : MonoBehaviour
{
public bool canThrow = false; // Player can toss le sword
public TMP_Text pressE;
public GameObject playerSword;
public GameObject ricochetObject;
public GameObject playerPos;
public bool isSwordThrowing; // track sword thrown and isnt picked up
void Start()
{
pressE.enabled = false; // Start with the "Press E" message hidden
playerSword.SetActive(false); // Player sword is initially inactive
ricochetObject.SetActive(false); // Ricochet script is initially inactive
}
private void Update()
{
ThrowSword();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("canPickup"))
{
Debug.Log("Player can pick up the sword");
pressE.enabled = true; // Show "Press E" when near the sword
}
}
private void OnTriggerStay(Collider other)
{
if (Input.GetKey(KeyCode.E) && other.CompareTag("canPickup"))
{
Debug.Log("Item picked up!");
// Deactivate the pickup object (set it to inactive)
other.gameObject.SetActive(false);
pressE.enabled = false;
// Activate the player's sword
playerSword.SetActive(true);
Debug.Log("Player sword is active");
// Set canThrow to true, meaning the player can now throw the sword
canThrow = true;
isSwordThrowing = false; // Sword is now back with the player, can be thrown again
}
}
public void ThrowSword()
{
if (canThrow && Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(0))
{
// Cache the sword's world position and rotation
Vector3 cachedPosition = ricochetObject.transform.position;
Quaternion cachedRotation = ricochetObject.transform.rotation;
// Activate the ricochetObject and deactivate the playerSword
Debug.Log("Throwing");
ricochetObject.SetActive(true);
playerSword.SetActive(false);
// Unparent the ricochetObject
ricochetObject.transform.SetParent(null, true); // The second parameter 'true' keeps the world position
// Re-apply the cached world position and rotation (to ensure it stays in place)
ricochetObject.transform.position = cachedPosition;
ricochetObject.transform.rotation = cachedRotation;
// Mark the sword as thrown
isSwordThrowing = true;
canThrow = false; // Sword cannot be thrown again until picked up
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("canPickup"))
{
Debug.Log("Nothing to pick up");
pressE.enabled = false; // Hide the "Press E" message when leaving the area
}
}
}