Hi guys,
Been working on a script to find the nearest object named ‘Weapon’ and pull it towards the player when a bool becomes true- I’ll develop this further once I’ve got it working, but at the moment I’m debugging with a raycast between the two objects.
However, for some reason when I set the bool ‘attach_weapon’ to true, my function for dealing with the location of the objects doesn’t work and a ray isn’t cast. I’ve checked and the public float distance_local doesn’t come back with anything.
My maths tells me subtracting the final vector from the initial vector gives the direction between objects and that I can calculate this as a distance as I have in the other part of the script using Mathf.Abs(MyVector.sqrtMagnitude). Here is my script so far.
Thank you for your time!
Popuppirate
using UnityEngine;
using System.Collections;
public class Weapon_Control_Script : MonoBehaviour {
public GameObject closest_weapon;
public bool attach_weapon;
public float distance;
public float distance_local;
// Use this for initialization
void Start () {
attach_weapon = false;
}
// Update is called once per frame
void Update () {
if (attach_weapon == false) {
SearchForWeapons();
}
if (attach_weapon == true) {
AttachWeapon();
}
}
void AttachWeapon(){ //Look Here!
Vector3 player_vect = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
Vector3 weapon_vect = new Vector3 (closest_weapon.transform.position.x,closest_weapon.transform.position.y,closest_weapon.transform.position.z);
Vector3 direction = (weapon_vect - player_vect);
float distance_local = Mathf.Abs (direction.sqrMagnitude);
Debug.DrawRay (player_vect, direction*distance_local, Color.green,1f);
//closest_weapon.rigidbody.AddForce (-direction * 4);
}
void SearchForWeapons(){ //This works lovely jubly
GameObject[] weapons = GameObject.FindGameObjectsWithTag ("Weapon");
distance = Mathf.Infinity;
for (int i=0; i<weapons.Length; i++) {
Can_Pick_Up canpickupscript=weapons*.GetComponent<Can_Pick_Up>();*
-
if (canpickupscript.can_pick_up==true){*
Vector3 diff_vect = weapons .transform.position - transform.position;
float diff_abs = Mathf.Abs (diff_vect.sqrMagnitude);
if (diff_abs < distance) {
closest_weapon = weapons ;
distance = diff_abs;
_ }
}_
* }*
* Debug.Log (closest_weapon.name);
_}*_
}