- Home /
Troubles with 2D projectiles
So, this is my first time working with 2D, and it's proving to be difficult for me. So here's the deal:
I have a script attached to the player that basically tells it to instantiate a bullet object at its position. Then that bullet has this script attached:
var speed:float = 2.0;
function Start()
{
var dir = Input.mousePosition;
transform.LookAt(dir);
}
function Update()
{
transform.position += transform.forward * speed * Time.deltaTime;
}
This script doesn't work how I want it to. At all. The bullet always moves to quadrant 1, if this were a graph, with the player being 0,0. That happens 100% of the time. To make matters worse, the bullet rotates so that the face of the sprite, with the texture on it, is facing the direction it's moving, so you can't see it at all from the bird's-eye perspective the game has. Does anyone have an explanation for this, and maybe a way to fix it so that it fires properly?
You can get projectile creation code from here: How to display projectile trajectory path in Unity 3D?
You have to change code to meet your requirement.
Answer by robertbu · Aug 27, 2014 at 03:53 AM
I'm assuming an Orthographic camera facing towards positive 'z', and the projectile is a Sprite where the front of the sprite is facing right when the Sprite's rotation is (0,0,0).
Change Start() as follows:
function Start()
{
var pos = Camera.main.WorldToScreenPoint(transform.position);
var dir = Input.mousePosition - pos;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
Note the 'WorldToScreenPoint()' call. The mouse lives in Screen coordinates, and your Sprite lives in world coordinates. You need to convert between the two when writing code like this.
Now... the rotation is correct, so thanks for that! The problem now, is that "transform.forward" makes it go along the Z axis, resulting in the bullet going underneath the player and staying in the same spot. How can I go about making it go... forward?
Edit: Never$$anonymous$$d! I've got it figured out. The answer was obvious, I'm just dumb. I have to use "transform.up" ins$$anonymous$$d. Also, I had to add "- 90" to the end of the angle variable, since the sprite texture is facing north.
Since the front of the projectile is the right side, use transform.right ins$$anonymous$$d of transform.forward:
transform.position += transform.right * speed * Time.deltaTime;
Your answer
Follow this Question
Related Questions
Fire Bullet To Mouse Position Problem 2 Answers
How to make my bullets spread when fired 3 Answers
scripting question 3 Answers
Turret bullet rotation problem 1 Answer
Fast bullet ignor collision sometimes 3 Answers