I have a robot with a wheel to which I have applied a script to rotate the wheel and a "wheel collider" component with these values:
I would like to know what values I have to modify to get the robot wheel to rotate at 30 rpm, since it is going to move around an office and it is seen to rotate very fast.
Finally, since it was a simple wheel and I just wanted it to give the effect of simple movement, what I did was this script.
public class WheelRotateAroundCylinder : MonoBehaviour
{
private Transform wheel;
private bool rotate = false;
private void Awake()
{
wheel = transform;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(rotate)
{
wheel.Rotate(0, -2, 0);
}
else
{
wheel.Rotate(0, 0, 0);
}
}
public void isRotate(bool hasRotate)
{
if(hasRotate)
{
this.rotate = true;
}
else
{
this.rotate = false;
}
}
}
Related
I've done it so far that when my player dies the level is restarted and I've written everything in the script but when I try it and the scene is reloaded everything is somehow extremely dark compared to before, although all settings from the camera etc. are the same and I don't know if I'm doing something wrong or if it's a bug
my Script:
public class GameManager : MonoBehaviour
{
public GameObject enemyPrefab;
// Start is called before the first frame update
void Start()
{
GameObject player = GameObject.Find("Player");
SpawnEnemy();
}
// Update is called once per frame
void Update()
{
RestartGame();
}
void RestartGame()
{
if(GameObject.Find("Player").GetComponent<PlayerMovement>().playerHealth <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
You need to bake your lighting inside your scene. Here are instructions on how:
Head to Window > Rendering > Lighting
Press Generate Lighting (Make sure Auto Generate is unselected)
Source
Your code has some trouble. But I'm not going to fix rotation issues. But here your working sample:
public class GameManager : MonoBehaviour {
public GameObject enemyPrefab;
// Start is called before the first frame update
void Start()
{
GameObject player = GameObject.Find("Player");
SpawnEnemy();
}
// Update is called once per frame
void Update()
{
RestartGame();
}
bool navigated = false;
void RestartGame()
{
if (!navigated)
{
if(GameObject.Find("Player").GetComponent<PlayerMovement>().playerHealth <= 0)
{
navigated = true;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
}
Pretty new to VR.I took a gameobject from an intial position by grabbing.When I grab a helmet and touch my body collider it hides the helmet.So next I may pick glasses and apply it to my body(Hides the GameObject).Next when I put the Incorrect Helmet the first helmet should go back to its initial position and should be seen in the scene.Similarily there are many GameObjects in the scene
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Helmet")
{
HideGameObject();
}
if (other.gameObject.tag == "Glasses")
{
HideGameObject();
}
if (other.gameObject.tag == "EarMuff")
{
HideGameObject();
}
if (other.gameObject.tag == "IncorrectHelmet")
{
HideGameObject();
}
if (other.gameObject.tag == "IncorrectGlasses")
{
HideGameObject();
}
if (other.gameObject.tag == "IncorrectEarMuff")
{
HideGameObject();
sendPickValues.Invoke(2, 0);
}
}
//Another script to set the GameObjects position
public class BackToPosition : MonoBehaviour
{
private Vector3 initialPosition;
private Quaternion initialRotation;
GameObject prevObject;
GameObject currObject;
// Start is called before the first frame update
void Start()
{
initialPosition = transform.position;
initialRotation = transform.rotation;
}
// Update is called once per frame
void Update()
{
}
public void BackToInitialPosition()
{
Debug.Log("Entered");
transform.position = initialPosition;
transform.rotation = initialRotation;
}
}
I am not trying to set the previous grabbed object to initial position.I may select wrong helmet first and pick many other matching gameobjects and later change to correct helmet.At that time first helmet should go to initial position.
This is a script that I use in SteamVR to grab and release a boat's rudder handle but it should be usable for you too:
[RequireComponent(typeof(Interactable))]
public class HandAttacher : MonoBehaviour
{
public UnityEvent OnGrab;
public UnityEvent OnRelease;
public UnityEvent OnHandEnter;
public UnityEvent OnHandLeave;
private Interactable interactable;
void Awake()
{
interactable = GetComponent<Interactable>();
}
/// this magic method is called by hand while hovering
protected virtual void HandHoverUpdate(Hand hand)
{
GrabTypes startingGrabType = hand.GetGrabStarting();
if (interactable.attachedToHand == null && startingGrabType != GrabTypes.None)
{
hand.AttachObject(gameObject, startingGrabType, Hand.AttachmentFlags.DetachFromOtherHand | Hand.AttachmentFlags.ParentToHand);
OnGrab?.Invoke();
}
}
protected virtual void OnHandHoverBegin(Hand hand)
{
OnHandEnter?.Invoke();
}
protected virtual void OnHandHoverEnd(Hand hand)
{
OnHandLeave?.Invoke();
}
protected virtual void HandAttachedUpdate(Hand hand)
{
if (hand.IsGrabEnding(gameObject))
{
hand.DetachObject(gameObject);
OnRelease?.Invoke();
}
}
}
Basically it creates Unity Events that you can add Listeners to in the Editor's Inspector window, or in code.
So in your use case, I would add a listener to OnRelease, and reset the GameObject's position and rotation to whatever it was before.
I tried using BackToPosition or something similar in Update comparing the original position to its current to reset the object's position, and the object keeps resetting on a loop instead of resetting to its original position and stopping.
Previously I had a script that I could look at a player but only when I had the Tab buttoned pressed down but could not cycle through enemies or anything. Looking all day for answers I came by this and decided it would be great I can now find things tagged enemies and cycle though them but I have not been able to figure out a way to lookat the enemy and stay looking at them and be able to move around them in a circle.
public class debug : MonoBehaviour
{
public List<Transform> targets;
public Transform selectedTarget;
public string targetTag = "Enemy";
private Transform myTransform;
//Use this for initialization
void Start()
{
targets = new List<Transform>();
selectedTarget = null;
myTransform = transform;
AddAllEnemies();
}
public void AddAllEnemies()
{
GameObject[] go = GameObject.FindGameObjectsWithTag(targetTag);
foreach (GameObject enemy in go)
{
AddTarget(enemy.transform);
}
}
public void AddTarget(Transform enemy)
{
targets.Add(enemy);
}
/*private void SortTargetsByDistance()
{
targets.Sort(delegate (Transform t1, Transform t2) {
return (Vector3.Distance(t1.position, myTransform.position).CompareTo)
(Vector3.Distance(t2.position, myTransform.position));
});
} */
private void SortTargetsByDistance()
{
targets.RemoveAll(target => target == null);
targets.Sort(delegate (Transform t1, Transform t2) {
return (Vector3.Distance(t1.position, myTransform.position).CompareTo)
(Vector3.Distance(t2.position, myTransform.position));
});
}
private void TargetEnemy()
{
if (selectedTarget == null)
{
SortTargetsByDistance();
selectedTarget = targets[0];
}
else
{
int index = targets.IndexOf(selectedTarget);
if (index < targets.Count - 1)
{
index++;
}
else
{
index = 0;
}
selectedTarget = targets[index];
}
}
//Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
TargetEnemy();
}
}
}
I am trying to use transform.LookAt(TargetEnemy); in void update but I get an error saying cannot convert from method group to transform. Im really stuck on this now any help is appreciated.
Edit: I am a big dummy I used transform.LookAt(selectedTarget); instead and the character for a split second will turn and lookat the enemy. Now i need to keep the player looking at the target and move around them.
Transform.LookAt
You need to pass it a Transform, not void.
TargetEnemy();
transform.LookAt(selectedTarget);
Alternatively, you can make TargetEnemy() return a Transform.:
private Transform TargetEnemy()
{
/* stuff */
return selectedTarget;
}
transform.LookAt(TargetEnemy());
Hello thanks to everyone that looked and thank #SonicBlue22 for your answer I figured it out after a couple more hours.
void Update()
{
if (Input.GetKeyUp(KeyCode.Tab))
{
TargetEnemy();
transform.LookAt(selectedTarget);
}
if (selectedTarget != null)
{
transform.LookAt(selectedTarget);
}
if (Input.GetKeyUp(KeyCode.Q))
{
selectedTarget = null;
return;
}
}
}
I am making sniper game, I have 2 cameras, one is rendering whole environment, and second one is in scope of the gun, which has high zoom quality.
I am able to show, enemy point on screen through main camera. and it shows proper on main camera, but in scope camera(2nd camera), it not showing properly. I want to show these points exactly same as enemy is.
here is my script to show point so far. I am attaching screen shots, first one is for scope camera and does not showing proper place, and 2nd one is for main camera, showing at proper place (Red circle is pointing)
using UnityEngine;
using UnityEngine.UI;
public class identity_shower : MonoBehaviour {
public Texture tex;
public GameObject helt;
public bool target_is_high =false;
private int counter_for_high = -1;
private int counter_for_low = -1;
private int counter_value = 50;
private bool bool_for_high = false;
private bool bool_for_low = false;
private Camera scope_cam_active;
private RectTransform rectTransform;
private Vector2 uiOFFset;
// Update is called once per frame
void OnGUI()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("enemy_soldier");
if( objs.Length<=0 )
{
return;
}
if (bool_for_high)
{
Vector2 pos_to_display = Camera.main.WorldToScreenPoint (this.transform.position);
GUI.DrawTexture (new Rect(pos_to_display.x-10.0f,(Screen.height- pos_to_display.y)-40.0f,15,15),tex);
}
}
public void show_your_identity()
{
if (target_is_high) {
if (counter_for_high >= counter_value)
{
return;
}
counter_for_high = counter_for_high + 1;
if (counter_for_high >= counter_value)
{
bool_for_high = true;
}
} else if(!target_is_high)
{
if (counter_for_low >= counter_value)
{
return;
}
counter_for_low = counter_for_low + 1;
if (counter_for_low >= counter_value)
{
bool_for_low = true;
}
}
}
}
I am trying to implement a Flame Thrower. I have setup the Particle System for flame. It is pooled object. It is not the child of the Flame Thrower. When I press the Fire button the particle system starts and when the button is up it stops. But a problem arised that when player is moving the particle system doesn't move . this was solved by adding the below line
particles.transform.position = transform.GetChild(0).position;
But the I discovered another problem that when rotating the player(This is a 2D sidescroller game) the particles are rotated with it instantly. So when the player changes the direction current particles are stopped and a new particle is activated and played. But now the problem is whenever I change the direction while pressing Fire buttons new objects are created.
The code of my flame thrower is
using UnityEngine;
public class FlameThrower : Gun
{
private ParticleSystem particles;
private int direction = 0;
private bool isFiring = false;
public override void Update()
{
if(shoot)
{
InitShoot();
}
else
{
StopFire();
}
}
public override void InitShoot()
{
if(!isFiring)
{
SelectDirection();
Fire();
}
//Check direction has changed
if(direction != playerManager.direction)
{
StopFire();
}
if(particles != null)
{
particles.transform.position = transform.GetChild(0).position;
}
}
public override void Fire()
{
isFiring = true;
direction = playerManager.direction;
InstantiateParticles(weapon.bulletName, transform.GetChild(0).position, rotation);
}
public override void SelectDirection()
{
if (playerManager.direction == 1)
{
rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, -90);
}
else if (playerManager.direction == -1)
{
rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, 90);
}
}
public override void InstantiateParticles(string name, Vector3 position, Quaternion rotation)
{
GameObject bullet = ObjectPooler.instance.GetObject(name);
while (bullet == null)
{
ObjectPooler.instance.CreateObject(name);
bullet = ObjectPooler.instance.GetObject(name);
}
if (bullet != null)
{
particles = bullet.GetComponent<ParticleSystem>();
//Set Position and rotation
bullet.transform.position = position;
bullet.transform.rotation = rotation;
bullet.SetActive(true);
particles.Play();
}
}
private void StopFire()
{
if (particles != null)
{
isFiring = false;
particles.Stop();
if(!particles.isPlaying)
{
particles.gameObject.SetActive(false);
particles = null;
}
}
}
}
The problem is that in the function StopFire() it checks whether particle is playing or not. If it is not playing it will disable the Gameobject. But it that part doesn't execute since it is checked soon after particles is stopped and it will still be playing. I want this particle system to be disabled as soon as it stops playing
It seems that the particle system is rendering in local space, that's why it rotates with the object.
Change the Simulation Space to World.
For the other issue, if you disable the game object then particles which are already emitted will disappear. And if you deactivates them with a delay (using Invoke or similar) then within that delay new particles can be emitted.
The best way to handle this is to stop the emission, not deactivating the game object. You can do this in inspector or via code. myParticles.emission.enabled
using UnityEngine;
public class ParticleSystemControllerWindow : MonoBehaviour
{
ParticleSystem system
{
get
{
if (_CachedSystem == null)
_CachedSystem = GetComponent<ParticleSystem>();
return _CachedSystem;
}
}
private ParticleSystem _CachedSystem;
public Rect windowRect = new Rect(0, 0, 300, 120);
public bool includeChildren = true;
void OnGUI()
{
windowRect = GUI.Window("ParticleController".GetHashCode(), windowRect, DrawWindowContents, system.name);
}
void DrawWindowContents(int windowId)
{
if (system)
{
GUILayout.BeginHorizontal();
GUILayout.Toggle(system.isPlaying, "Playing");
GUILayout.Toggle(system.isEmitting, "Emitting");
GUILayout.Toggle(system.isPaused, "Paused");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Play"))
system.Play(includeChildren);
if (GUILayout.Button("Pause"))
system.Pause(includeChildren);
if (GUILayout.Button("Stop Emitting"))
system.Stop(includeChildren, ParticleSystemStopBehavior.StopEmitting);
if (GUILayout.Button("Stop & Clear"))
system.Stop(includeChildren, ParticleSystemStopBehavior.StopEmittingAndClear);
GUILayout.EndHorizontal();
includeChildren = GUILayout.Toggle(includeChildren, "Include Children");
GUILayout.BeginHorizontal();
GUILayout.Label("Time(" + system.time + ")");
GUILayout.Label("Particle Count(" + system.particleCount + ")");
GUILayout.EndHorizontal();
}
else
GUILayout.Label("No particle system found");
GUI.DragWindow();
}
}
This might help you in playing,pausing and fully stopping your particle system from emitting particles.
Hope i helped.