Original question on the Unityforums here
I've been trying to get an animation to not only slow down and speed up, but also play backwards depending on user input for my Hololens-application. I am using the Mecanim system, not legacy animations.
The whole thing is supposed to happen at runtime, through dynamic user input.
I know that it's possible through scripting, as I had it working before I lost local progress and some files during some Unity-Collaborate issues. As stupid as it sounds, since then I have not been able to remember what I did different from my current approach.
Right now I'm manipulating the value Animator.speed, but that only works for values >= 0.
Any help would be greatly appreciated!
Edit: In case the link is not working or visible for anybody, here is my code:
private Animator anim;
//...
anim = gameObject.GetComponent<Animator>();
//...
public void OnManipulationUpdated(ManipulationEventData eventData)
{
if (anim.isActiveAndEnabled)
{
anim.speed = eventData.CumulativeDelta.x;
anim.Play("KA_Cover_Anim");
return;
}
//...
}
Edit2: Incorrectly marked as dupicate! The linked question does not regard a similar problem and required a different solution
Edit3: For clarification, the linked "duplicate" uses the legacy animation system which is irrelevant for my question. In Mecanim, the new animation system in Unity 5.xx, you can not access the Animations directly as shown in the selected answer. Neither is it possible to alter the animation speed as shown in in the second answer.
I'm not exactly sure what you're end goal is, but you can play animations backwards and at different speeds by using a parameter.
On the animation state, you can make it watch a parameter and multiply it against the default speed of the animation. All you need to do in code is something like
animator.setFloat("Speed",-1.0f);
Hope that helps.
Related
I am facing some issues with working with the "new" Unity input system. I am working on an FPS prototype, where the player can pick up different guns with different windup times. I do not want to keep track of how long the player has held the shoot key, as the Hold interaction can do that by itself.
Looking around Unity documentation, MS Intellisense suggestions, and Stackoverflow, I have not seen a single instance of something around the lines of "Override interactions of InputAction". It is simply something not being talked about. Should I take that as a red flag for what I am doing is wrong? Probably.
I can see the interactions field for an InputAction, but it is marked with the readonly keyword. There is no internal setter for it either. Otherwise, the solution would be trivial, though unusual to the Unity™ way.
float duration = 0.04f;
controls.Main.Shoot.interactions = $"Hold(duration={duration})";
// Error: "Interactions" is readonly
Is there really not a way to edit the interactions for an InputAction during runtime with code?
I'm currently developing a game in Unity using C# and I've run into a small problem.
I need to spawn a certain gameobjects relative to the Spawnposition and length of another game object. Now I figured that bounds.size would be the best function to use in this instance. As shown bellow I declare first the variable that uses this in my start method:
public void Start()
{
GameObject PointBar = (GameObject) Resources.Load("PointBar Horizontal");
PointBarVectorLength = PointBar.GetComponent<BoxCollider2D>().bounds.size.x;
PointBarVectorConv = Camera.main.WorldToViewportPoint(new Vector2(PointBarVectorLength, 0f));
}
However, the gameobjects in question are inactive at start's call and thus I presume don't return any value for bounds.size when called.
Does anyone know how I can access the bounds.size or equivalent of an inactive gameobject or is there something else I'm missing here?
As noted in the documentation for the Collider.bounds property, bounds "will be an empty bounding box if the collider is disabled or the game object is inactive". So your assumption was pretty much right. Since the object doesn't exist in worldspace that makes sense.
I'm not sure about the most elegant solution for your use case but two options spring to mind.
Calculate the object's spawn dimensions by accessing its transform.localScale and factoring in the scale of prospective parent objects. That could get messy but you could probably also write a helper method to make it more manageable.
Instantiate the object somewhere off screen after you load it, access its Collider.bounds property to get the information you need then move it where ever you want it or store the information for later.
There may be better solutions but that's what leaps to mind for me.
I solved the issue by using GetComponent().bounds.size.x;
instead of BoxCollider. This component can get accessed when the game object is not active.
I'm making a mobile clone of pacman for android. Everything is working fine, but I am trying to optimize my game as much as possible.
Currently in some scripts I am finding GameObject's by doing GameObject.Find() in the Start() function of my scripts, like this:
void Start()
{
ghosts = GameObject.FindGameObjectsWithTag("Ghost");
pacman = GameObject.Find("Pacman");
gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
}
My question is, would performance increase if I made some of these GameObject's inspector assigned variables instead of doing .Find()?
Would that increase the performance speed or would it make no difference seen as though I do a .Find() in the Start() function?
Obviously performance would decrease if it was called in the Update() as the script would try and find a GameObject every frame, but a Start() function would only search for it once?
Performance at startup for this kind of things is totally negligible, Inspector assignment requires deserialization, while Find requires message dispatch, both are slow operations, if you think that matters, profile that.
I would anyway use
FindObjectOfType<GameManager>() as GameManager
wich is at least more typesafe, I would not use editor inspection if possible, because manual wiring is source of many little errors. So I give a human-time performance reason:
Do not use editor inspection because if you miss to wire something you will have to debug a nullpointer wich on the long run will eat hours of your time.
You have anyway to use Editor Insection in cases where you do not have just to find 1 component, no workaround for that (unless you use Svelto or Svelto-ECS wich are rather advanced topics.)
I am fairly new to code, I know some of the basics but my knowledge is limited, so please let me know WHY in your answer if it's not too hard to explain, I'd like to learn rather than just be given the answer!
This code is the basic controls for a game i am making. I'll be explaining the premise of the game just so you're able to better grasp what my intent is.
The game will focus on the completion of mazes, however movement is restricted to only being able to go forward, and right. You may never do a u-turn, go left or go backwards.
With my current code, it is possible (VERY EASILY POSSIBLE) to just translate over the entire maze and the colliders for walls don't apply due to it being a translate, which to my understanding is essentially 'teleporting' it.
I've looked around on similar topics and discussions but I was unable to find any answers that addressed this kind of issue with colliders.
When the object collides with a 'wall' in my maze, I want the object to be reset to it's original position, or at the very least die, I'm not sure if that will affect the answer given, but just incase keep that in mind, thank you!
using UnityEngine;
using System.Collections;
public class Movement_Script : MonoBehaviour {
public float playerspeed = 1;
void Update () {
if(Input.GetKeyDown("up"))
{
transform.Translate(Vector3.up * 1);
}
if(Input.GetKeyDown("right"))
{
transform.Translate(Vector3.right * 1);
transform.Rotate(Time.deltaTime,0 ,-90);
}
}
}
When you control the transform, you are telling "Place this there".
So when you do:
transform.Translate(Vector3.up * 1); // multiplying by one is useless
you tell to displace the object by 0,1,0 from its current position. This is regardless of any environment. You still can detect collision by it won't be resolve by the engine, you would have to do it yourself.
Unity came up with a ready to use solution with the character controller component. It does the same as you do in your code but also perform a bunch of collision checks and resolve them. The latest version is actually using rigidbody for a more physical approach.
http://docs.unity3d.com/Manual/class-CharacterController.html
http://docs.unity3d.com/ScriptReference/CharacterController.Move.html
the Move method is the one to use for Unity to handle the whole process for you. I would recommend to install a basic four wall room with a few boxes here and there so that you get the grip of it. Then it will be easy to move on to do whatever you want with it, whether 2D or 3D movement.
I am working on Unity for a month. I am new on Unity and C#, before Unity I worked other game engines. Whatever I am working on infinite run game, I wrote random road generator. Road generator is working well but I have problem about updating road. I can update road manualy like this. How can I update it automaticly?
void Update()
{
if(Input.GetKeyDown(KeyCode.A)) UpdateRoad();
}
My UpdateRoad method adding road like this(I am using object pooling).
I want to update after Link Road, OnExitTrigger or something I dont know. How can I do it?
You would need to implement Object Pooling.
I would suggest making your Design of Objects first so you can test. Or if not use, the stock Blocks Primitive of Unity3D as your Prefabs. I hope you already know prefabs. It is a major key for making infinite runner. Actually a main core for making any kinds of game.
Prefabs is an Object File where you can Instantiate it in a location. So lets say you will generate a Flat walkable, then Generate a Pit. You would probably want to stack them together.
Now Generating them is easy. You would not like to go in an Update? Approach because most likely you're not going to update, but you're going to further stack what is going on ahead, based on your game logic.
To further Understand this, Unity3D already made a project or Fully Detailed tutorial. It maybe made in 2D but it is going to be the same, if you're going to change the Collider2D to Collider <- this is important in your case.
https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/infinite-runner
Update
You would need to create an Object, that is invisible. Meaning a Trigger.
Then on Trigger call your method UpdateRoad();
https://unity3d.com/learn/tutorials/modules/beginner/physics/colliders-as-triggers
Detailed Videos about Trigger.
If I understood your needs correctly, you could create Empty Object name it SpawnPoint, set position for Spawn Point as you need (out of the camera view) and then Instanciate random prefabs of road. Concerning On TriggerExit - it could be used to destroy "old piece of road". But to have it working properly, dont forget to set collider and rigitbody to your objects. Dont add collider2D or Rigitbody2d, add and use Box Collider and Rigitbody components