0
\$\begingroup\$

The game is a top down 2d shooter and I'm facing trouble in doing this : - I got a player 2D ship - The player fires laser, which is a long thin image with box collider attached. - What I want is that when the laser hit the enemy ship, the laser's length (Height) should be equal to the distance between the player and the enemy. (That is the laser shouldn't go through the enemy)

So what I have done is this : In the Laser's script : Vector3 scale = new Vector3(1, 1, 1);

void OnCollisionStay2D(Collision2D col) { If (col.gameObject.layer == 12) //ENEMY { scale.y = (col.gameObject.transform.position.y - Info.PlayerPosition.y) / this.gameObject.renderer.bounds.size.y; this.transform.localScale = scale; }

void OnCollisionExit2D(Collision2D col) { scale.y = 10 / this.gameObject.renderer.bounds.size.y; // 10 is the height of the screen; this.transform.localScale = scale; }

That's it. So when I run it, things go crazy, the scale.y value kind of oscillates between some low value and high value and withing 2-3 seconds, scale.y becomes infinity (as of Unity Console)

I can't make anything out of it :( Been like 1.5months with unity. Thanks in advance :)

\$\endgroup\$
5
  • \$\begingroup\$ Please edit your question to make the code more readable. Instead of using <code> use 4 spaces before a line that is code. The 4 Spaces will force all the text up to the nect linebreak (when you press Enter) to be monospaced and with a grey background. I personally found that for further intendation (eg after a { ) you can use 4 Spaces again and your code will look much cleaner (and is in most cases easier to understand). \$\endgroup\$ – JFBM Sep 13 '14 at 8:35
  • \$\begingroup\$ You might want to look into raycasting. This will give you (with some math) the distance from your gun to the enemy. Use this distance for scaling. \$\endgroup\$ – JFBM Sep 13 '14 at 8:52
  • \$\begingroup\$ As it is a 2D game, I think just the difference in the y-component of the player and the enemy would do, right ? How does the value gets into infinity ?? That's what bothers me.. :O *and sorry for the code, I am posting this from mobile \$\endgroup\$ – faztp12 Sep 13 '14 at 15:34
  • \$\begingroup\$ As @Larethian mentioned use raycast. In the approach you are following on which gameobject have you attached your lazerscipt?docs.unity3d.com/ScriptReference/Physics2D.Raycast.html \$\endgroup\$ – 2600th Sep 13 '14 at 19:34
  • \$\begingroup\$ Use ray casting with a line renderer \$\endgroup\$ – Savlon Sep 14 '14 at 4:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.