- Home /
Firing a projectile in 2D
I am attempting to make a 2D catapult that fires at a certain angle depending on where the user drags the mouse cursor to from a starting position.
I have managed to get it semi working with the code below but it provides qute unusual behaviour (the projectile never fires on the correct dragged angle). Any ideas?
var ClickDown : Vector3;
var ClickUp : Vector3;
var point : Vector3;
var pooPrefab : Transform;
var multiplier : float;
function OnMousedown(){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (collider.Raycast (ray, hit, 100.0)) {
ClickDown = hit.point;
}
}
function OnMouseUp(){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (collider.Raycast (ray, hit, 100.0)) {
ClickUp = hit.point;
}
FirePoo();
}
function FirePoo () {
var projectile = Instantiate (pooPrefab, ClickUp, Quaternion.identity);
var shootVector = ClickDown - ClickUp;
projectile.rigidbody.velocity = shootVector * multiplier;
}
Depending on the objects in your scene, you aren't necessarily firing in 2D. Are your ClickUp & ClickDown vectors what you expect them to be?
Yeh the object fires on the X/Y axis, the problem is that on mouse up the ball fires correctly from the end position, however it does not fire in the dragged angle if that makes sense. Imagine an angry birds style catapult the fires in a random direction (its not meant to though)
Since you are using Physics to drive the motion there are a myriad of settings that could cause your motion to be not as expected. Here's a random list of things to try or check.
If you want the object to be constrained to the X,Y plane you can constrain the Z position & rotation.
You can attempt to use http://unity3d.com/support/documentation/ScriptReference/Rigidbody.AddForce.html ins$$anonymous$$d of setting the velocity directly.
Ensure both the drag and angular drag settings are what you intend.
Ensure your gravity is going the direction you intend.
Unfortunatly it seems none of those work, is there a different way i could replicate this mechanic i am attempting that you know of?
Your answer
Follow this Question
Related Questions
How do I fire a 2D projectile based on it's current angle/location. 1 Answer
Calculate third Vector3 with two Vector3s and an Angle 1 Answer
Shooting projectiles in 2D world 2 Answers
How to get rotation for projectile to fire at cursor? 1 Answer
c# 2D top down, fire projectale which continuously move in a direction 3 Answers