简体   繁体   中英

How Can I Pull Back To Shoot A 2D Sprite? (C# + Unity)

I'm having a bit of trouble working out how to get a simple pull back to shoot script on my 2D circle sprite, I know the idea behind it, but I can't work out the code exactly.

I've got this half working using the angry birds clone script inside of Unity's 2D pack asset, but that relies on another object and linked with a spring joint, it works in a way, but if I try to shoot it slowly and on specific angles, it will shoot backwards instead of the way it was intended to go.

Also I need the script to be just on the ball itself so that when the ball stops moving, it can be shot again from that location.

Here's what I'm thinking is the solution but can't work out the exact code for:

Mathf.Atan2(ballStartY - ballCurrentY, ballStartX - ballCurrentX). Then maybe flip it by adding 180 somehow?

Then use the angle to break it down into x and y components (xSpeed = cos(angle) * force) and (ySpeed = sin(angle) * force) perhaps?

I also need to use the mouse position on click like I've got happening to move the ball and make it kinematic while it's being clicked on and also lock it so you can't pull it back further than a specified float amount.

I really appreciate any help you can give! Thanks everyone!

If I understand correctly you have Three problems making the object move, letting the object be re-thrown when it is stopped,and how to pull the object to launch it.

So for the first one if you rotate the ball so that the x axis of the local cords is in the direction you want to shoot then you can use this code to make the ball fly forward at some magnitude indicated by the vector3. The force mode is impulse because you want instantaneous force.

gameObject.GetComponent<Rigidbody>().AddRelativeForce(9,0,0, ForceMode.Impulse);

The rotation should be simple with the look at function. The documentation of such is here you then rotate that 180 with the quaternion function. you use that with the mouse position to get something like this:

rotation = Quaternion.Euler(180, 0, 0) * Input.mousePosition;
transform.LookAt(Rotation);

Then just use an if for finding out if you are clicking to activate it. If you want to show it being pulled back use Vector3.Distance with an if statement like:

if(Vector3.Distance(thisGameobeject, someParentObjectThatWontMoveWhenPulledBack)<50)
{pull further back}

As for checking if your are stopped you could use an if statement with Rigidbody.velocity and that should just about cover everything. I hope this at least helps a little bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM