• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by caleb_b · Sep 16, 2014 at 01:24 AM · c#raycastfpsbullet

Make my gun model fire bullets

I've done this before, when I first started with Unity, as a complete beginner to game development. The problem is that the tutorial I followed to do it was written in Javascript, and I write with C# now that I have more experience. I tried to translate the Javascript to C# but to no avail.

I snagged a model of a pistol off of the Asset Store, and threw this script on it.

 using UnityEngine;
 using System.Collections;
 
 public class PlayerGunController : MonoBehaviour 
 {
     public GameObject projectile;
     public int speed = 10;
     public int ammo;
     public RaycastHit hit;
 
     void Update() 
     {
         if(Input.GetKeyUp(KeyCode.S)) 
         {
             projectile.transform.position = hit.point;
         }
     }
 }

As I'm sure you've guessed, it doesn't work. I click the button and the capsule I assigned as "projectile" disappears(The way it is positioned, it sticks out notably from the gun model). I have no idea where it goes from there. I've tried Frame-by-frame but I just can't see.

If I had to guess, I'd say the problem has a lot to do with the raycast, but I'm at a loss from there.

I appreciate any help. "Do this" type answers are good, but I'd prefer an explanation if that's possible. Thanks peeps!

Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Sep 16, 2014 at 01:31 AM 0
Share

There is no Physics.Raycast() call here, so this code takes an uninitialized RaycastHit structure and accesses the uninitialized 'hit.point'. I believe 'hit.point' in this situation will be Vector3.zero, so you code just moves the projectile to Vector3.zero in world space.

avatar image caleb_b · Sep 16, 2014 at 02:29 AM 0
Share

Alright, bit of an update. I made some edits to my code after looking up Physics.Raycast() at your mention. I discovered that I needed arguments, so I kinda just winged it. I'm shooting in the dark, in case you couldn't tell :) New code:

 using UnityEngine;
 using System.Collections;
 
 public class PlayerGunController : MonoBehaviour 
 {
     public GameObject projectile;
     public int speed = 10;
     public int ammo;
     public RaycastHit hit;
 
 
 
     void Update() 
     {
         Vector3 fwd =  transform.TransformDirection(Vector3.forward);
         if(Input.GetMouseButtonDown(0)) 
         {
             if(Physics.Raycast(transform.position, fwd, Mathf.Infinity))
             {
                 projectile.transform.position = hit.point;
             }
         }
     }
 }

Nothing appears to have changed. I click the mouse button, and the capsule disappears. Having the scene view and game view windows side by side with the capsule object highlighted, I noticed that when I click, the capsule drops below the terrain and follows the character around from there. I have the capsule parented to the gun, which is parented to the main camera from the stock FPS Controller.

avatar image Cherno · Sep 16, 2014 at 02:50 AM 0
Share

Before changing the transform.position of the bullet, you have to set it's parent to null.

projectile.transform.parent = null;

As for the movement, you are still not lerping the bullet but rather make it go to the hit.point position instantly from one frame to the next.

BTW, you can just use transform.forward as the raycast vector3.

avatar image caleb_b · Sep 16, 2014 at 03:26 AM 0
Share

Thanks for that^^ But I'm a little confused... The few times I've seen Lerping in use(in tutorials and such) it was only a couple of lines of code. THis is what's in the link you gave me

 using UnityEngine;
 using System.Collections;
 
 public class ExampleClass : MonoBehaviour {
     public Transform startMarker;
     public Transform endMarker;
     public float speed = 1.0F;
     private float startTime;
     private float journeyLength;
     public Transform target;
     public float smooth = 5.0F;
     void Start() {
         startTime = Time.time;
         journeyLength = Vector3.Distance(startMarker.position, endMarker.position);
     }
     void Update() {
         float distCovered = (Time.time - startTime) * speed;
         float fracJourney = distCovered / journeyLength;
         transform.position = Vector3.Lerp(startMarker.position, endMarker.position, fracJourney);
     }
 }

By my understanding, I'd need to declare the start point(the player's position)and the end point(The raycast hit point?), plus another bit to actually perform the process. The example code in the documentation seems really intensive for doing something as simple as that. What I'm asking is, do I really need all 20 odd lines in the example?

avatar image Cherno · Sep 16, 2014 at 03:34 AM 0
Share

No, it can just be a simple while... loop in a simple Coroutine with only abour four variables.

There are a lot of tutorials on this so you will just have to read a bit :) After all, it is one of the most basic and often-used functions in Unity.

    private bool moving;
 public float speed = 2.0f;
 public Vector3 targetPos;

 void Update() {

     if(moving == false) {
         moving = true;
         StartCoroutine(Move(targetPos);
     }
 }

 IEnumerator Move(Vector3 newPos)
 {

     for (float t = 0.0f; t < 1.0f; t += Time.deltaTime * speed) {
         transform.position = Vector3.Lerp(transform.position, targetPos, t);
         yield return null;
     }
             moving = false;
 }

Where targetPos would be hit.point. You use the portion

         if(moving == false) {
         moving = true;
         StartCoroutine(Move(targetPos);
     }

whenever you want to set the bullet in motion (so, after pressing the fire button for example).

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Cherno · Sep 16, 2014 at 01:32 AM

First of all, I don't see where the raycast is actually cast :) I assume you cast it when the gun is fired, and want the bullet to travel to the point that the ray hit. Ok so far, but you only set the bullet's transform.position without any smooth movement. You can use Vector3.Lerp, for example. It's explained further in the Unity Scripting API.

http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

25 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Distribute terrain in zones 3 Answers

Ray.direction editing not working in C#? 1 Answer

Where can i find an easy raycast shooting tutorial for C#? 2 Answers

Raycasting to avoid falling (FPS game) 2 Answers

shooting multiple enemies using raycast 2 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges