- Home /
Shooting at mouse position
Hi guys I need some help with my code, it's a simple 2d shooter, I want the player to shoot in the direction the mouse is pointing, this is my code:
if(Input.GetButtonDown("Fire1")){
var mouse = Input.mousePosition;
mouse.z = 1.0; //diobonino
var mouseworldpos : Vector3 = Camera.main.ScreenToWorldPoint(mouse);
mouseworldpos.y = transform.position.y;
Debug.Log(mouseworldpos);
var bullet_dir : Vector3 = mouseworldpos - transform.position;
bullet_dir = bullet_dir.normalized;
var clone = Instantiate(bullet1,transform.position + bullet_dir * 2,Quaternion.LookRotation(mouseworldpos, Vector3.forward));
clone.GetComponent(Rigidbody).AddForce(bullet_dir * bullet_speed);
}
My first problem is that sometimes it shoots in the direction of the old mouseposition, especially when the player is moving. My secondo problem is the rigidbody, is there another way to shoot bullets that can detect collision without using rigidbody?
Thanks everybody
Answer by ThePunisher · Oct 04, 2012 at 12:14 AM
Answering second problem here...
If you don't need to simulate bullets in real time then you could simply use RayCasting to get the behavior for a shooter. All you would need in this case would be a collider component (like box/mesh colliders).
Try the following script. Add it to any GameObject, like the main camera. Then create a cube and place it somewhere where your camera can view it. Separate your scene and game views so that you can view both simultaneously and hit play. Left-Click around the game window and you'll see a red line is drawn on the scene view. Any time you click on an object with a collider you'll see a debug message come up with the name of the GameObject you hit. Let me know if this would work for what you want to do and I can help you customize it further.
using UnityEngine;
using System.Collections;
public class Shooter : MonoBehaviour
{
private Ray ray;
private RaycastHit hit;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 25.0f))
{
Debug.Log(string.Format("Hit: {0}!", hit.transform.gameObject.name));
}
else
{
Debug.Log("Missed!");
}
}
Debug.DrawLine(ray.origin, ray.direction * 25.0f, Color.red);
}
}
I think that simulates the fire of a really fast bullet (I just call a behaviour if the ray interpolate with an object), I need to instantiate a bullet that might react to an hit
Hmm, alright. Well then are you sure this is correct "var bullet_dir : Vector3 = mouseworldpos - transform.position;"?
Your answer
Follow this Question
Related Questions
Can't shoot towards mouse click point 1 Answer
Help First Person Shooter Bullets instantianion 2 Answers
The code is giving me errors 1 Answer
Shoot directions 2 Answers
Adding movement speed of Player to 1 Answer