Setting Animation frame number without playing - c#

I want to set the animation frame without playing it currently i am doing this it work perfectly but can i make it possible without playing the animation?
GO.GetComponent<Animation>().Play("Start");
GO.GetComponent<Animation>()["Start"].time = ((1f / 30f) * 0);
GO.GetComponent<Animation>()["Start"].speed = 0;

My advice would be to create a new state that simply contain that one frame.
It is counter-intuitive to think of a state that is stuck on its first frame. It is like saying you are int eating state but only holding the fork without any movement. Something is not quite right in that statement.
So you'd rather have a Immobile state and then run it in loop. When you need to start doing other actions, then just switch as would.
Now if you want to start an animation at a specific position:
animator.Play("AnimName",layer, normPosition);

Related

How to play animation forward and backward in Unity?

Hello there :) I'm making a 2d platform game with Unity and got stuck with the crouch animation... I have quite a few frames for crouching, so, when player presses appropriate button character sits down and when the button is released I want this animation to be played backward, so, character stands up. Currently in the animator I created two states with the crouching animation assigned to them. Crouch state speed is 1 and so called un-crouch one is -1 which sort of works fine. My inner perfectionist's question: is there more elegant solution for this kind of cases that allows not to "duplicate" states?
Thank you in advance!
Something you can try is to add in your script a parameter to multiply the speed of the animation. You can call this parameters animDirection or something like this.
I am not sure if you want to speed up the animation as well, but just in case you can do something like this:
float animSpeed = 1;
float animDirection = 1;
Now you can manipulate in your script this variables, to make the animation move faster and also forward (animDirection = 1) or backward (animDirection = -1)
gameObject.animation["crouch"].speed = animSpeed * animDirection;
So with this you don't need to have two different states.

How to reset sequence of animations when target is lost

I am using Unity and Vuforia, and would like to make an animation on AR object that starts when target is found and resets when target is lost so that, when target is found again the animation starts from the beginning.
In order to make animation start only once target is found, I selected the option "Cull Completely" in the Culling Mode property of the animator component. But I can't manage to reset the animation when target is lost ! I have tried modifying the DefaultTrackableEventHandler script (the OnTrackingFound and OnTrackingLost methods) but it doesn't work.
So far I have tried :
Animation[] animationComponents = GetComponentsInChildren<Animation>();
foreach (Animation component in animationComponents)
{
component.Stop();
}
and some variations (animation name as a parameter of Stop method, animator component instead of animation component, ...).
Does someone know how to do this ?
Thanks for your attention :)
I know a way of doing what you want in a simpler way. Look for https://docs.unity3d.com/Manual/class-State.html
You will get the same results but in a different way using the animation states.
Then go to the animator window
And you can build something like that. Those are transitions between states, associated to an animation.
Take a look at this too https://docs.unity3d.com/Manual/class-Transition.html
So in your script you can access to the Animator with:
Animator MyAnimator = GetComponent<Animator>();
And in somewhere over your conditions in the game, you can do this:
MyAnimator.Play("Attack");
If that animation doesn't have a transition, it will your decision to make it a loop animation (it will repeat when ends) or it will stay in the position of the last frame of the animation.
With some conditions you might want to have, like the one in your question, you could do something like this.
if (Vector3.Distance(this.transform.position, myTarget.transform.position) >= 2f) {
MyAnimator.Play("Idle");
}
Warning: That Vector3.Distance may not be the best and fastest way of doing it, it's just as an example. Remember to always try to optimize your code with your project requirements.

Changing Sprites using scripts in Unity2D C#

I am wanting to make a birds-eye view pixel-art game.
I currently have two sprite sheets set up, and split and whatnot
groundSheet and characterSheet these are split up into
ground_0_0_0 (A concrete floor)
ground_1_0_0 (grass)
character_0_0_0 (man idle animation frame 1)
character_0_0_1 (man idle animation frame 2)
character_0_1_0 (man run animation frame 1)
character_0_1_1 (man run animation frame 2)
character_1_0_0 (woman idle animation frame 1)
character_1_0_1 (woman idle animation frame 2)
character_1_1_0 (woman run animation frame 1)
character_1_1_1 (woman run animation frame 2)
The numbers after are a note as to:
first number - the main set of sprite animations (eg man)
second number - the animation set in use (eg run or idle)
third number - the frame of said animation.
(the ground has this as i plan to have animated grounds late on)
Now, I wish to make a script for the character (and ground alike) that has an editable value that is view able in the unity editor, for example how things like the sprite renderer has sprite, colour etc. Which dictates what first number to use (see above) what second number and the delay for the animation of the third number. This will then tell the sprite renderer what pictures to load and how quickly to load them. I also wish for the script to scan for the file starting with for example character_0_0_ and then count how many files after it, so it knows what to do when animating. I would like this script to be checking for a change in one of the variables viewable in the unity editor to change and as soon as it does it checks everything it needs for an animtion.
Something else could be done where there is only 1 box to edit in unity, which you put character_0_0_ or ground_1_0_ or something similar, and it checks everything that way (it also makes the script universal, and usable on the ground, character and walls (which I am adding later)).
This may seem confusing, but it make sense for me and many of you will probably mention a much easier way to do animations and such, but please only say these if it does what I want above.
For scripts and such my file layout:
/Assets
/scripts
ground.cs
character.cs
/sprites
characterSheet.png
character_0_0_0
character_0_0_1
character_0_1_0
character_0_1_1
character_1_0_0
character_1_0_1
character_1_1_0
character_1_1_1
groundSheet.png
ground_0_0_0
ground_1_0_0
(For some reason Stack overflow said the above was code, so i had to make it as that)
ground.cs and character.cs are the scripts in which I want to made as explained above.
In my object view thingy I have
Main Camera
ground
character
I am practically a newb to C# and JS I know bascially the grammar of C# (like where to use {} and put ; at the end of the lines). If you help me with this, i request that you explain the script, like use the // thing to simply explain what each command does, I know a few but not all of them. And I know someone is going to say it is really well documented in tutorial X and such, but most tutorials are not in unity 5 and while helping with the matter do not touch on it exactly.
Thank you for your help, if there is anything about this question/request that you do not understand (It is pretty complex) I will explain.
Maybe I am completely wrong, but it seems to me that you are trying to recreate an Animation system.
Is there a specific reason for which you wouldn't use Unity's animation system?
You can do everything that you describe here with it (change sprite, choose animation speed). And you would have almost no code to write. Just drag and drop you sprites in the editor for a start
EDIT - answer to first comment:
What you should do is create all the animations you need. Then in the animator, you choose which condition will trigger a transition to another animation (for instance, boolean jump is true will transition to animation jump). Then in your code you can call GetComponent().SetBool("Jump", true).
To have different character, you can create different gameObjects (one per character). They all have a different animator with animations specific to the character.
The other solutiojn if you really want one one gameObject and one animator is that you also add string condition to you animation (example, if character=="character1" and jump==true, transition to jump animation).
If I were you I would really focus on testing and learning all you can do with Unity animator. I can't think of a case were you would need to recreate the animation system yourself
Your question was long winded and hard to understand but ill try to help,
firstly if you want editable values in the unity editor I would Suggest using a serialized structure of information like this
[System.Serializable] // this makes it viewable in the inspector
public struct Sprite_Manager;
{
public Sprite[] Render_Sprites; // array of sprites to store sprites
public SpriteRenderer S_Renderer;
public float Anim_Delay;
}
public class Character : MonoBehavior {
Sprite_Manager SMG = new Sprite_Manager(); // instantiate a new instance of the struct
void Set_Sprite()
{
for(int i = 0; i < SMG.Render_Sprites.Length; i++)
{
SMG.S_Renderer.sprite = SMG.Render_Sprites[i];
}
}
void Update
{
Invoke("Set_Sprite", SMG.Anim_Delay);
}
}
Not sure if this is exactly what your looking for but this is one way you could setup a structure of sprite based information and use Invoke to setup some sort of delay when passing new sprites to the renderer.

XNA Slow down Animation

I am making the character run but the animation is extremely quick as I am doing:
_frameIndex++;
_frameIndex; is the value which points to the image in the SpriteSheet. Does anyone know how I can use gameTime.ElapsedGameTime.TotalMilliseconds to slow the animation down?
I saw that you've asked a couple of questions tonight concerning animation and spritesheets, so here's an example from Aaron Reed's "Learning XNA 4.0," from Chapter 3 under the "Adjusting the Animation Speed" heading.
First, create two class-level variables to track time between animation frames:
int timeSinceLastFrame = 0;
int millisecondsPerFrame = 50;
The first variable tracks time passed since the animation frame was changed, and the second is an arbitrary amount of time that you specify to wait before moving the frame index again. So making millisecondsPerFrame smaller will increase the animation speed, and making it larger will decrease the animation speed.
Now, in your update method, you can take advantage of game.ElapsedGameTime to check time passed since the last frame change, and change the frame when when that value greater than millisecondsPerFrame, you can do work:
timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
if (timeSinceLastFrame > millisecondsPerFrame){
timeSinceLastFrame -= millisecondsPerFrame;
// Increment Current Frame here (See link for implementation)
}
This sort of solution is similar to what you've found works, except that you can take an extra step to specify exactly how often you want the animation to update, or even change that duration later on in your code if you like. For example, if have some condition that would "speed up" the sprite (like a power-up) or likewise slow it down, you could do so by changing millisecondsPerFrame.
I removed the code that actually updates the current frame, since you should already have something that does that since you have a working animation. If you'd like to see the example in-full, you can download it from the textbook's website.
I debugged the code and noticed that the gameTime.ElapsedGameTime.TotalMilliseconds always equated to 33. So I did the following:
milliSeconds += gameTime.ElapsedGameTime.Milliseconds;
if (milliSeconds > 99)
{
_frameIndex++;
milliSeconds = 0;
}
Which basically means that if this is the THIRD frame of the game, then make he _frameIndex go up. Reset the milliseconds to start over.

Generate multiple images from one c#

I'm making a side-scrolling Mega Man based game in C#. I am NOT using the XNA frame work to do so. I'm looking at creating multiple "bullets" from one location using one single image within my game class. The only thing I can think of at this point is something similar to this:
if (shooting == true)
{
BulletLocation.X += 3.0F;
Bullet = Properties.Resources.Bullet;
Charecter = Properties.Resources.shooting;
}
Shooting is set true on the keyDown event, and set to false on the keyUp event. I'm positive i would need an array of the sorts, but I'm not sure exactly how I should go about it. Thanks for your help!
EDIT:
What portion of that code would actually allow you to generate multiple "bullets" from one sprite single sprite? When the user presses the space bar, I would like to create a bullet that moves forward until it reaches the end of the screen. I can do that part easily. I cannot, however, do it with multiple bullets. I can only have one bullet alive at a time. I'm not sure how I would go about creating multiple bullets on the forum from one single image.
If I understand it correctly, you want to show multiple bullets, right?
I would make a variable for # of bullets and bulletposition.
So lets say:
const DISTBETWEENBULLETS = 3.0;
int distToOpponent = 9.0:
int curBulletDist = 0;
do{
curBulletDist += DISTBETWEENBULLETS;
//Draw bullet
}while(distToOpponent <= curBulletDist);
I hope this helps, and if it doesn't answer your question, or you mean something else, feel free to ask.

Categories

Resources