- Home /
Shooting at an object
So I was looking around for a bit of code that lets you shoot towards an object. This worked well for what I'm doing. Here is what I've found:
void FixedUpdate ()
{
rigidbody2D.velocity = (GameObject.Find("Game_Center").transform.position - transform.position).normalized * speed;
}
Although I find myself scratching my head as to how or why this works. Is there someone who can tell me so I may better understand it? Thanks in advance.
Answer by APenguin · Feb 06, 2014 at 01:45 PM
So this script is attached to what? I am not very clued up about unity scripting, but from experience in c#, i would guess that transform.position is a vector. So you have the center, and you minus the position of the shot from the center. You then normalize which gives you the direction of the Vector. Then you multiply the vector by the speed which makes the shot move towards that direction.
It's attached to a sprite that represents a "bullet". This makes sense. I think I really wasn't sure about what normalize does. But that cleared it up for me thanks.
Remember though that normalize just gives a direction and not the length e.g. Vector2(0,0,1) -> This is a direction.
Answer by APenguin · Feb 06, 2014 at 02:32 PM
All this does it it finds the direction using the center and the position of the shot. It the multiplies the vector by the speed. Whatever answer it gets it is then put into the RigidBody2D velocity. I hope i am right, but i am sure it is.
APenguin :)
Your answer
Follow this Question
Related Questions
Shooting around defense position without contact 1 Answer
Bullet disappears for no reason 2 Answers
need help with 2d shooting -1 Answers
How to destroy only one GameObject??? 0 Answers
Start timer with Input 2 Answers