I’m having a tough time getting this to work, i’m trying to create a 2D gun of sorts, depending on what direction the flashlight is pointed in it should instantiate an orb and shoot that orb in the direction its pointing. I cant seem to use the existing position though, any ideas? Thanks!
private void turnFlashlight()
{
Vector3 Temp = new Vector3(0f, 0f, 0.0f);
Vector3 Target = new Vector3(Input.GetAxis("rHorizontal")*360,-Input.GetAxis("rVertical")*360, 0f);
if ( Target.sqrMagnitude > m_deadzone * m_deadzone )
m_lookTarget = Target;
if (!CharacterSettings.paused)
{
flashlight.transform.LookAt(m_lookTarget);
if(Input.GetAxis("RTrig")>0){
Debug.Log("hit");
GameObject go = Instantiate(prefab, null, this.transform);
Vector3 newPos = Vector3.MoveTowards(go.transform.position, new Vector3(0,0,0), Speed * Time.deltaTime);
go.transform.position = newPos;
}
else if(!(Input.GetAxis("RTrig")>0)){
}
}
}
@3kWikiGames let me know if it works for you. Also, make sure to delete the tesing regions. They are only there for, well… Testing purposes. Happy coding!
This is the script attached to my gun:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
[SerializeField] private KeyCode kShoot; // Key to press for the gun to shoot.
[SerializeField] private GameObject bulletPrefab; // Prefab of the bullet with a Rigidbody attached. The gravity on the Rigidbody is disabled.
[SerializeField] private Transform bulletSpawn; // An object with a transform located at the end of the gun. Bullet is spawned on this location.
[SerializeField] private float bulletSpeed; // How much force to add to the bullet when it is instantiated.
[SerializeField] private float shootDelay; // Minimum wait time between shots. Value is in seconds.
private bool canShoot;
#region Testing
[SerializeField] private KeyCode kRotateCW, kRotateCCW; // Keys for rotating the gun. Used only for testing.
[SerializeField] private float rotSpeed = 5f;
#endregion
private void Start()
{
canShoot = true;
}
private void Update()
{
if (Input.GetKeyDown(kShoot) && canShoot)
{
StartCoroutine(Shoot());
}
#region Testing
if (Input.GetKey(kRotateCW))
{
transform.Rotate(transform.forward * rotSpeed * Time.deltaTime);
}
if (Input.GetKey(kRotateCCW))
{
transform.Rotate(-transform.forward * rotSpeed * Time.deltaTime);
}
#endregion
}
private IEnumerator Shoot()
{
canShoot = false;
GameObject newBullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
newBullet.GetComponent<Rigidbody2D>().AddForce(newBullet.transform.right * bulletSpeed, ForceMode2D.Impulse); // We use the right (or up in some cases) transform because forward in a 2D space is into the screen.
yield return new WaitForSeconds(shootDelay);
canShoot = true;
}
}
These are the values I used:
The bulletSpawn is a child of the gun and is placed like this: