- Home /
Possible to create a Function Within Update(); ?
Hi guys,
I have a Noobish error that is hard to explain but I'll try my best. I am using C#
I have a line of code that translates a gameObject with a material on it that I'm using to make it look like its shooting a bullet forward.
transform.Translate (Vector3.right* Time.deltaTime *moveSpeed);
Now to shoot left and right in my 2D Platformer, On keypress I would change Vector3.right
to Vector3.left
To determine if I'm facing Left or right I have made a bool that already checks if im facing left or right by checking the GameObject.Position.localScale.x if it is (-1,1,1)
or (1,1,1).
of my character.
The end code will look like this.
if (facingRight == true) {
transform.Translate (Vector3.right* Time.deltaTime *moveSpeed);
}
else
{
transform.Translate (Vector3.left* Time.deltaTime *moveSpeed);
}
Which looks simple and it does work, kinda. - the Problem I'm having is that once the Sprite is busy being translated over time (moving forward) and If I turn the character and the bool updates to facingRight = false. Then the gameObjects will start translating in the other direction in mid air.
I know this is because its checking the bool inside the update function so it is updating every frame. But how would I Check the bool from outside the Update(); function and call just
transform.Translate (Vector3.left* Time.deltaTime *moveSpeed);
which needs to be updated every frame. Can i make that a variable or something? I know I cant create it as a function WITHIN the update Function.
I hope this makes sense.
Razz
Answer by Pascal97 · Jul 17, 2015 at 09:43 AM
Why don't you simply instantiate a new GameObject with your character when the player presses the shooting button, and give that object a certain velocity that cannot be changed. So maybe devide your script in the palyer script that will create the bullet with a certain velocity and then simply let the bullet fly in the direction the velocity points.
Instatiate: http://docs.unity3d.com/ScriptReference/Object.Instantiate.html
You could also Instantiate a different bullet depending on the direction the player is pointing to. So when the player looks right instatiate a bullet with a script that makes it fly to the right and vice versa.
I hope this helps... :)
HI Pascal,
I managed to solve it using a similar method to that! Thanks for the answer! ;)