How to let gravity work in editor mode in Unity3D - c#

I am wondering is there any way to let gravity affect items in editor mode? Normally I set the rigidbody to a object and hit play button, then I can see the object will be falling according to gravity. But How can I do this without hitting play button?
I googled a lot and I can't find any document showing me how to do it.
Thanks

This answer by ThePilgrim on the Unity Q&A site seems to answer this question:
You can simulate physics in the editor by setting
Physics.autoSimulation to false, and using Physics.Simulate() to
advance physics frame by frame until your objects are settled.
Here is an example editor window:
using UnityEditor;
using UnityEngine;
public class ScenePhysicsTool : EditorWindow {
private void OnGUI()
{
if (GUILayout.Button("Run Physics"))
{
StepPhysics();
}
}
private void StepPhysics()
{
Physics.autoSimulation = false;
Physics.Simulate(Time.fixedDeltaTime);
Physics.autoSimulation = true;
}
[MenuItem("Tools/Scene Physics")]
private static void OpenWindow()
{
GetWindow<ScenePhysicsTool>(false, "Physics", true);
}
}

I use this asset called 'Editor Physics Simulator' from the Unity asset store.
Link to asset: https://assetstore.unity.com/packages/tools/level-design/editor-physics-simulator-221538
It only simulates non-kinematic Rigidbodys.
You can simulate all selected Rigidbodys, or ones that are the child of a selected GameObject, or all Rigidbodies at once.
You can simulate for a set amount of time (with interrupts) or manually as long as you want, and you can even still undo/redo the simulation with the default Unity editor keybinds.
It also lets you record animation clips of the physics simulations.

Related

cant play an animation when pressing a button

screen shot of the animator panel
so as you can see I am trying to play an animation called Attack when triggering the parameter Attack but whenever I press the triggering button that I chose the animation just doesn't work and the trigger does not get activated
here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class attack : MonoBehaviour
{
public Animator animator;
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
Attack();
}
}
void Attack()
{
animator.SetTrigger("Attack");
}
}
by the way, I am trying to follow this guy's video
https://youtu.be/sPiVz1k-fEs
Suggestions:
Make sure you have assigned this script to a game object.
Assign the right animator that you want to animate in inspector of this script.
Check if you have added 'Attack' parameter in that animator and the spelling is same like the one mentioned as parameter in your code.
and lastly check if you have set the trigger for the transition of animation in the animator( in animator its the arrow that is pointing towards your animation ).
Let me know if you don't understand any of this I'll breifly explain.
Hopefully that will help... Happy coding :)

Animate an object by pressing Key / or Mouse Click Unity3D

currently i'm trying to animate an object by clicking or pressing a key. Unfortunately, script won't work and I have tried soooooo many other ways to do it.
Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurnBoard : MonoBehaviour
{
public Animator anim;
void Start()
{
anim = GetComponent<Animator>();
}
void OnTriggerStay(Collider player) {
if (player.tag == "Player" && Input.GetKeyDown(KeyCode.G)){
//Debug.Log("touchyy");
anim.SetTrigger("turn");
}
}}
I have assigned this script file to object itself. Object has a box collider. Animation has a trigger named "turn". When player enters to the collider zone, I want player to be able to activate animation of the object with a click/or keypress.
I do get "Debug.Log" when player enters the zone. So I believe that there is no problem in detecting the collision. But just can't manage to animate object in any way.
Any help? Thank you!
OnTriggerStay is run like FixedUpdate (since it involves physics), so none of the Input events will work correctly inside it for the same reason that they won't work right in FixedUpdate. All Input functions must only be used in Update method.

How to make animation repeat on every keypress in unity (Unity3d, C#)

I am new to C# and Unity and I'm trying to figure out how to make an animation for an object in unity play when I press a key but I can only make the animation play once, and then it is broken and doesn't work. (I am trying to make an FPS game)
The code I have right now looks like this:
void Start()
{
gameObject.GetComponent<Animator>().enabled = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
gameObject.GetComponent<Animator>().enabled = true;
}
}
When I press run and left click, the animation triggers and does as it is supposed to but when I try to do it again, the animation doesn't work. Can anybody help me change this code so that the animation will work and play every time the button is pressed?
I am assuming your animation is non-looping as if it was looping it would already play back into itself when it is over.
One quick note I would have with your code is do not use GetComponent in an Update function as it is quite costly. An easy way to get an animation state to reset is to enable and disable it, however I am assuming you want to have more animations than shooting. You would want to look into what is called an Animation Tree or a Blend Tree and add States to your animation. Examples of states would be an Idle, Walk, Run, Shoot, Crouch, etc. I would consider researching Animation Trees and Blend Trees to get a full animation cycle in.
Once you get a State machine working, I would have the enter go to an Idle state, then either set a transition Bool or directly switch the animation in code.
// when you serialize a private field, it will appear in
// the inspector so you can drag in the reference in the editor
[SerializeField] private Animator anim = null;
private void Start()
{
anim.enabled = false;
}
private void Update
{
if(Input.GetButtonDown("Fire1")
{
Shoot();
if(!anim.enabled)
anim.enabled;
else
anim.Play("AnimationStateName", -1, 0f);
}
}
I have not tested the code, but I believe this would work with your setup. I would still strongly advise to not do this and look into Trees. After implementing the tree, instead of calling using the enabled, just use the line anim.Play("AnimationStateName", -1, 0f) or you can do anim.SetBool(isAttacking, true) if you set your state to transition from Idle/Run/Walk/etc. to Attacking when the isAttacking bool is set to true.
I found a video that might help you out. I do not want to post a full explanation to animation states and blend trees, just point you in the right direction to a better approach.

Switching Between OVRPlayerControllers in Unity 2019.2.4f1

Versions: Unity v2019.2.4f1, Oculus Utilities v1.41.0, OVRPlugin v1.41.0, SDK v1.42.0
I am in the process of creating an Oculus Rift game where the player can use buttons to toggle between walking around on the ground and looking around in a bird's eye view of the environment. To accomplish this, I am using the following script to toggle between two different OVRPlayerControllers, one positioned on the ground and one positioned in the air looking down:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraSwitcher : MonoBehaviour
{
public GameObject firstPersonCameraPrefab;
public GameObject overheadCameraPrefab;
void Update()
{
bool isDownOne = false;
bool isDownThree = false;
isDownOne = OVRInput.GetDown(OVRInput.Button.One);
isDownThree = OVRInput.GetDown(OVRInput.Button.Three);
if (isDownOne || isDownThree)
{
switchCam();
}
}
public void switchCam()
{
overheadCameraPrefab.SetActive(!overheadCameraPrefab.activeInHierarchy);
firstPersonCameraPrefab.SetActive(!firstPersonCameraPrefab.activeInHierarchy);
}
}
At the start of the game, the first person player is active, and the overhead player is not active. When I use this script, the headset toggles between looking through the two cameras. However, the connection between the game and the movement controls on the controllers gets severed after the first switch. When I toggle back down to the ground, I can no longer use my controllers to move my player around.
How can I switch between players and keep the movement controls in tact?
This is because you have more than 1 OVRManager in your scene, the prefab OVRCameraRig has 1 attached, so if you have more than one of this prefabs, like 2 players, Oculus won't work correctly.
Put the component in an empty prefab that never turns off, and set switch between your player controllers freely.

What's stopping my camera movement script from receiving input events?

Thanks for reading. I tried posting this on unity answers, but it's been 24 hours and it's still not out of moderation, so maybe I'll have better luck here.
Background
I am very new to unity and know I must be missing some critical piece of knowledge to tie this together. I've created a blank game with some placeholder terrain and added a main camera to the 3d orthographic scene. I would like the user to be able to move the camera along a parallel plane to the ground.
What I've Done
I've added a starter camera codebehind I found online along with an event system, rigid body, ray caster, and a bunch of other things I saw online for this sort of thing. All of these components are in the same layer.
The Problem
My camera script's update method is hit when I put that in for testing but it doesn't receive any other events even though it implements the appropriate interfaces. I'm guessing I have something blocking the input from hitting the script or I do not have a component I need in order for those events to fire.
I'm testing on desktop for now but I want this to run on mobile (although from what I've read the events I'm subscribing to should be universal). Can anyone spot any oversights or deficiencies in my setup so far? Here are some screenshots.
Thanks!
My Setup
Edit: by request, here is the camera script I'm using. I know it doesn't do what I want yet but the issue I'd like to tackle right now is why it doesn't seem to be wired up correctly. Like I said, if I put an update method in here it is hit but none of my other logs are hit.
using UnityEngine;
using UnityEngine.EventSystems;
// The touch is in 2D but the scene is in 3D, so touch.x => scene.x, touch.y => scene.z, and nothing change (0) => scene.y since y is up
public class TouchCamera : MonoBehaviour,
IPointerDownHandler,
IDragHandler,
IPointerUpHandler
{
private Vector3 prevPointWorldSpace;
private Vector3 thisPointWorldSpace;
private Vector3 realWorldTravel;
private int drawFinger;
private bool drawFingerAlreadyDown;
public void OnPointerDown(PointerEventData data)
{
Debug.Log("Pointer down");
if (drawFingerAlreadyDown == true)
return;
drawFinger = data.pointerId;
drawFingerAlreadyDown = true;
prevPointWorldSpace = data.pointerCurrentRaycast.worldPosition;
// in this example we'll put it under finger control...
GetComponent<Rigidbody>().isKinematic = false;
}
public void OnDrag(PointerEventData data)
{
Debug.Log("Pointer drag");
if (drawFingerAlreadyDown == false)
return;
if (drawFinger != data.pointerId)
return;
thisPointWorldSpace = data.pointerCurrentRaycast.worldPosition;
realWorldTravel = thisPointWorldSpace - prevPointWorldSpace;
_processRealWorldtravel();
prevPointWorldSpace = thisPointWorldSpace;
}
public void OnPointerUp(PointerEventData data)
{
Debug.Log("Pointer up");
if (drawFinger != data.pointerId)
return;
drawFingerAlreadyDown = false;
GetComponent<Rigidbody>().isKinematic = false;
}
private void _processRealWorldtravel()
{
Debug.Log("Updating camera position");
Vector3 pot = transform.position;
pot.x += realWorldTravel.x;
pot.z += realWorldTravel.y;
transform.position = pot;
}
}
Final Edit for the Solution
Thank you very much to Juan Bayona Beriso for helping me in chat with this configuration. Here is what we ended up with that now works:
The camera object has a Rigidbody and Physics 2D Raycaster attached to it. The scene now has a new Canvas object with a Graphics Raycaster (blocking mask set to everything and blocking objects set to none) and an event system with the standalone input module enabled. That canvas also has a child UI object that covers the screen and has the camera script attached. As a curiosity, it required a text component in order for the script to start receiving the events -- this only made a difference when the Raycast Target option was selected. Screenshots below.
I think you are misusing the EventSystem, OnPointerDown, OnDrag and all those functions, they are called when you have a PhysicsRaycaster in your Camera object and you press or drag over an UI Element or and object with a collider.
In your code you don't have any of these, you have a camera so you are not actually pointer down over it or dragging on it.
You have two options:
Either put this script in a plane with a collider or GUI element that is inside the camera and moves with it, or use Input.GetMouseButtonDown, Input.GetMouseButtonUp in the Update function

Categories