• 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
Question by Kaltic · Jun 16, 2011 at 06:44 AM · 2dbulletprojectileshootmouse cursor

Projectile move towards mouse cursor

I'm not looking for answers on how to make my character face my mouse cursor, but just so the bullet coming from the character will move towards where my mouse cursor was when it shot. The game is currently a 2d top down shooter and all my bullets do is essentially act like bombs. The instantiate, but do not move.

What code I have is here.

 function BulletShot(){
     var BulletClone = Instantiate(bullet, transform.position, Quaternion.identity);
     rigidbody.AddForce(transform.forward * BulletSpeed);
     Physics.IgnoreCollision(BulletClone.collider, collider);
 
 }
Comment

People who like this

0 Show 0
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

3 Replies

· Add your reply
  • Sort: 
avatar image

Answer by Oliver Eberlei · Jun 16, 2011 at 10:57 PM

You can create a plane and do a raycast against it to get the current mouse position in 3d space (at y = 0)

T$$anonymous$$s is C#, shouldn't be too hard to convert to JavaScript

 if( Input.GetMouseDown( 0 ) )
 {
     Plane zeroPlane = new Plane( Vector3.up, Vector3.zero );
     Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
     float distance;

     if( zeroPlane.Raycast( ray, out distance ) )
     {
         Vector3 outputPosition = ray.origin + ray.direction * distance;
         Debug.Log( "Position: " + outputPosition  );

         //You can use t$$anonymous$$s position to rotate the bullet like so
         BulletClone.transform.LookAt( outputPosition );
     }
 }

If you want the resulting position at a different height than zero, change the Vector3.zero in the first line.

Comment

People who like this

0 Show 2 · 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
avatar image Kaltic · Jun 23, 2011 at 09:33 PM 0
Share

I am having a couple of issues in changing this over to JavaScript.


if( zeroPlane.Raycast( ray, out distance ) )

 {
     Vector3 outputPosition = ray.origin + ray.direction * distance;

That is confusing me quite a bit. First off is am assuming i am creating a variable called distance which is a float and not doing something such as Vector3.distance.

But then what is "out distance", I have been looking at the Unity scripting documentation and it isn't helping me out with understanding it. The actual Raycast has "out enter : float" anyway, but no matter what I put I still get errors.

And with the Vector3 outputPosition. Am I creating a variable Vector3 called outputPosition? Even if I am I haven't found a way to write it without just getting errors.

avatar image Oliver Eberlei · Jun 23, 2011 at 09:52 PM 0
Share

damn, deleted my comment -.- again

The out keyword is a C# construct (not sure if its the same in JS) which causes arguments to be passed by reference. This means the Raycast function can change the distance paramenter, and it will be changed outside the Raycast function as well.

Regarding the output position: Yes, this is a vector we create via the following calculation

 ray.origin + ray.direction * distance; 

(Note: ray.direction always has the length 1)

In simpler terms, by starting at

 ray.origin (which is where we started our raycast) 

and adding

 "direction of ray" times "distance of hitpoint from origin" 

we end up at the world position where the ray hit the plane.

avatar image

Answer by aldonaletto · Jun 24, 2011 at 01:04 AM

If you're making a top down shooter with the camera set at some height and looking down to the ZX plane (rotation = 90,0,0), t$$anonymous$$s script will shoot in the direction of the point the mouse is on. Don't forget to uncheck Use Gravity in the rigidbody:

 var bullet:GameObject;
 var BulletSpeed:float = 20;
 
 function BulletShot(){
 
     var myPos = transform.position;
     var dist = Camera.main.transform.position.y-myPos.y;
     var x = Input.mousePosition.x;
     var y = Input.mousePosition.y;
     var dir = Camera.main.ScreenToWorldPoint(Vector3(x, y, dist))-myPos;
     var BulletClone = Instantiate(bullet, myPos, Quaternion.LookRotation(dir));
     BulletClone.rigidbody.velocity = dir.normalized * BulletSpeed;
     Physics.IgnoreCollision(BulletClone.collider, collider);
     Destroy(BulletClone,5);
 }
 
 function Update(){
 
     transform.Rotate(0,Input.GetAxis("Horizontal")*60*Time.deltaTime,0);
     transform.Translate(0,0,Input.GetAxis("Vertical")*10*Time.deltaTime);
     if (Input.GetButtonDown("Fire1")){
         BulletShot();
     }
 }

It also included the movimentation instructions, but you can replace them with your own code.

Comment

People who like this

0 Show 1 · 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
avatar image Kaltic · Jun 24, 2011 at 04:31 PM 0
Share

Actually I am on the x,y plane. So I need the bullets to be able to move 360 degrees around my character while they don't actually do that with that code. If you are asking why I had transform.forward in my script, then don't ask it should have been that anyway.

avatar image

Answer by Dreamblur · Jun 24, 2011 at 01:33 AM

The problem with your code is t$$anonymous$$s line here:

 rigidbody.AddForce(transform.forward * BulletSpeed);

rigidbody (unless it was explicitly overridden) is the access variable to the rigidbody of the game object to w$$anonymous$$ch your script is attached to. Since your bullet is being instantiated from wit$$anonymous$$n t$$anonymous$$s script, then it's quite obvious that t$$anonymous$$s script is not attached to your bullet -- and even if were, the function would have to be called again for rigidbody to start referring to the bullet's own rigidbody, in w$$anonymous$$ch case you'd have a second bullet with the same problem. You need to access the rigidbody of the bullet that you just instantiated, not the rigidbody of the bullet instancer.

So you basically want somet$$anonymous$$ng like t$$anonymous$$s:

 BulletClone.rigidbody.AddForce(transform.forward * BulletSpeed);

But that doesn't solve all your problems.

You see, that line is inside the same function w$$anonymous$$ch instantiates the bullet, w$$anonymous$$ch means that it gets called after the bullet is instantiated and never again (not for the same bullet). And since you didn't pass a ForceMode parameter, then that will be set to the default value of ForceMode.Force. There's not$$anonymous$$ng wrong with that, but I'm t$$anonymous$$nking that's not what you want. Considering that ForceMode.Force was meant to be used so that force can be applied over several frames, I'm 100% sure that that's not what you want. What you actually want to do is apply an initial velocity to the bullet, w$$anonymous$$ch you do by passing either ForceMode.Impulse or ForceMode.VelocityChange as the ForceMode parameter.

As for the issue of wanting the character to face the cursor, the others have already addressed that. I haven't perused the actual code w$$anonymous$$ch they posted, but I'm too lazy to do so, so let's just say that I trust them. XD

Comment

People who like this

0 Show 0 · 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

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Problem creating a 2D scroller shooting game 2 Answers

How to avoid speed change in bullets while moving? 1 Answer

2d shooting Left / Right 1 Answer

Fire a Projectile towards a specific object? 1 Answer

Shoot Bullet At Touch Position : 2D 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges