I am a beginner in Unity and following Udemy tutorials for learning VR using Unity and making a game named Ninja Slash. Everything seems to be working fine in the Unity Editor Play mode but when I run my app in a real device, my player doesn't move at all. I can't figure out what is the problem here.
Here is my Player script.
public class Player : MonoBehaviour {
public GameObject sword;
public float speed = 4.5f;
public float walkingAmplitude = 0.25f;
public float walkingFrequency = 2.0f;
public float swordRange = 1.75f;
public float swordCooldown = 0.25f;
public bool isDead = false;
public bool hasCrossedFinishLine = false;
private float cooldownTimer;
private Vector3 swordTargetPosition;
// Use this for initialization
void Start () {
swordTargetPosition = sword.transform.localPosition;
}
// Update is called once per frame
void Update () {
if (isDead) {
return;
}
transform.position += Vector3.forward * speed * Time.deltaTime;
transform.position = new Vector3(
transform.position.x,
1.7f + Mathf.Cos(transform.position.z * walkingFrequency) * walkingAmplitude,
transform.position.z
);
cooldownTimer -= Time.deltaTime;
if (GvrViewer.Instance.Triggered ) {
RaycastHit hit;
if (cooldownTimer <= 0f && Physics.Raycast(transform.position, transform.forward, out hit)) {
cooldownTimer = swordCooldown;
if (hit.transform.GetComponent<Enemy> () != null && hit.transform.position.z - this.transform.position.z < swordRange) {
Destroy (hit.transform.gameObject);
swordTargetPosition = new Vector3 (-swordTargetPosition.x, swordTargetPosition.y, swordTargetPosition.z);
}
}
}
sword.transform.localPosition = Vector3.Lerp (sword.transform.localPosition, swordTargetPosition, Time.deltaTime * 15f);
}
void OnTriggerEnter (Collider collider) {
if (collider.GetComponent<Enemy> () != null) {
isDead = true;
} else if (collider.tag == "FinishLine") {
hasCrossedFinishLine = true;
}
}}
Here is the screenshot for hierarchy view.
I tried with different version gvr sdk unity package but I am getting same result everytime and I also tried running it different devices like htc,samsung etc.
I believe you can't change the transform of the main camera in VR mode. You have to make the maincamera as a child of another object (empty?!) and then move that object.
Related
I am new to game development, i am trying to to change my code to mobile touch. I tried to change the flowing code to make workable for mobile touchscreen unfortunately failed. can you help me how can I make flowing code for mobile?
Here is the code.
Vector2 newPos;
bool canMove = true;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
newPos = transform.position;
}
private void Update()
{
if (canMove)
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
newPos.x += 1.4f;
transform.position = newPos;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
newPos.x -= 1.4f;
transform.position = newPos;
}
}
if (Input.GetKeyDown(KeyCode.Space) && canMove)
{
rb.AddForce(Vector3.down * speed);
canMove = false;
}
Vector2 clampPos = transform.position;
clampPos.x = Mathf.Clamp(transform.position.x, -2.1f, 2.1f);
transform.position = clampPos;
}
Create a Canvas with a screen wide transparent Image component inside.
Use OnPointerDown and OnDrag event functions to catch finger movement on this image. Just make your class implement IPointerDownHandler and IDragHandler interfaces and use PointerEventData args properties to get delta or current position.
You can use the code below. Add it to the screen wide image and assign your Ridigbody2d and transform in inspector.
public class Movement: MonoBehaviour, IPointerDownHandler, IDragHandler
{
public Rigidbody2d rb;
public float maxSpeed = 10f;
public float sensitivity = 0.1f;
public float xBound = 2.1f;
Vector3 initialFingerPosition;
bool canMove = true;
public void OnPointerDown(PointerEventData pointerEventData)
{
initialFingerPosition = pointerEventData.position;
}
public void OnDrag(PointerEventData data)
{
if(!canMove)
return;
var position = rb.position;
position += data.delta * sensitivity * speed * Time.deltaTime;
position.x = Mathf.Clamp(position.x, -xBound, xBound);
rb.MovePosition(position);
}
}
In my game I want to have one of my enemies move towards the player however they don't do that for some reason. The enemy is supposed to look at the player and when the player enters the range they should start moving towards him. My problem is that they aren't doing anything. They just stand there. Also they don't even fall when they have a rigidbody. It currently has an Animator, box collider, and a capsule collider.
Edit: I forgot to add this but the script also triggers the animations
Edit #2: Also I know that it isn't because the movement is in the if statement
(Sorry if it is bad I am a programmer noob)
This is the script responsible for the players movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mar_Tracker : MonoBehaviour
{
public Transform Player;
public float MoveSpeed = 3.0f;
public float InRadius = 250.0f;
public float AttackRange = 11.0f;
public float rocketRange = 50.0f;
private Animator anim;
private Coroutine RocketLouch = null;
public GameObject Rocket;
public GameObject Explosion;
public SphereCollider sphereCollider;
private void Start()
{
anim = GetComponent<Animator>();
Player = GameObject.FindGameObjectsWithTag("Player")[0].transform;
sphereCollider.enabled = false;
}
void Update()
{
Player = GameObject.FindGameObjectsWithTag("Player")[0].transform;
transform.LookAt(Player); // Makes it so that the enemy looks at player
float dstSqr = (Player.position - transform.position).sqrMagnitude;
bool inRadius = (dstSqr <= InRadius * InRadius);
bool inAttackRange = (dstSqr <= AttackRange * AttackRange);
bool inRocketRange = (dstSqr <= rocketRange * rocketRange);
anim.SetBool("inArea", inRadius);
anim.SetBool("Attacking", inAttackRange);
if (inRadius)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime; // (movement)
}
if (inRocketRange)
{
if (RocketLouch == null)
{
RocketLouch = StartCoroutine(RocketLaunch());
}
}
}
IEnumerator RocketLaunch()
{
anim.SetBool("Rocket", true);
yield return new WaitForSeconds(0.15f);
sphereCollider.enabled = true;
Explosion.SetActive(true);
yield return new WaitForSeconds(1.0f);
anim.SetBool("Rocket", false);
Destroy(Rocket);
}
}
Your using math that may be a tad to complicated for what you want to achieve and I think the issue is happening there.
Lets simplify it
Transform Player;
float InRadius;
float AttackRange;
float rocketRange;
void Start()
{
// Set it at the start to optimize performance
Player = GameObject.FindGameObjectsWithTag("Player")[0].transform;
}
// Use fixed Update for moving things around
// Better performance
void FixedUpdate()
{
HandlePlayerDetection() ;
}
void HandlePlayerDetection()
{
transform.LookAt(Player); // Makes it so that the enemy looks at player
// Find the distance between the player and the transform
var distance = Vector3.Distance(transform.position, player.position);
// Do the boolean calculations
bool inRadius = distance <= InRadius;
bool inAttackRange = distance <= AttackRange;
bool inRocketRange = distance <= rocketRange;
// Lets use inbuilt functions to movement
if (inRadius)
{
transform.position = Vector3.MoveTowards(transform.position, Player.position, MoveSpeed * Time.deltaTime);
}
// Rocket code
if (inRocketRange)
{
FireRocket();
}
}
void FireRocket()
{
if (RocketLouch == null)
{
RocketLouch = StartCoroutine(RocketLaunch());
}
}
Now if you really want your enemy to walk properly I would recommend watching a tutorial on Nav Meshes. It is super easy to use and will allow the enemy to walk around objects and do propper path finding.
Hello everyone and thanks in advance for your answers!
I am a beginner in unity, coding my second game after i finshed a couple of tutorials.
Since today, i noticed that suddenly all my "GameObjects" have a "UnityEngine." in front of them.
I have no idea how that happened, and it is also not just in one script, but all of them. Heres an example of it:
UnityEngine.GameObject item = (UnityEngine.GameObject)Instantiate(itemGOList[i], spawnTransform, spawnRotation);
This worked fine before without the "UnityEngine.", but now it only works when its written this way.
Do you know how this could have happened and how to revert it?
This is one of the scripts:
using UnityEngine;
using UnityEngine.EventSystems;
public class Turret : MonoBehaviour
{
private Transform target;
private Enemy targetEnemy;
[Header("General")]
public float range = 10f;
[Header("Use Bullets/missiles (default)")]
public UnityEngine.GameObject bulletPrefab;
public float fireRate = 1f;
private float fireCountdown = 0f;
public AudioClip shootingSound;
private AudioSource audioSource;
[Header("Use Laser (default)")]
public bool useLaser = false;
public int damageOverTime = 20;
public float slowAmount = .5f;
public LineRenderer lineRenderer;
public ParticleSystem impactEffect;
public Light impactLight;
[Header("Unity Setup Fields")]
public string enemyTag = "Enemy";
public Transform partToRotate;
public float turnSpeed = 10f;
public Transform firePoint;
void Start()
{
InvokeRepeating(nameof(UpdateTarget), 0f, 0.3f); // Call the UpdateTarget Method after 0 seconds, then repeat every 0.3 seconds.
audioSource = GetComponent<AudioSource>(); //Puts the AudioSource of this GO (the turret) into the variable audioSource.
}
void UpdateTarget ()
{
UnityEngine.GameObject[] enemies = UnityEngine.GameObject.FindGameObjectsWithTag(enemyTag); // Find all enemies (and store in a list?).
float shortestDistance = Mathf.Infinity; // Create a float for the shortest distance to an enemy.
UnityEngine.GameObject nearestEnemy = null; // Create a variable which stores the nearest enemy as a gameobject.
foreach (UnityEngine.GameObject enemy in enemies) // Loop through the enemies array.
{
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position); //Get the distance to each enemy and stores it.
if (distanceToEnemy < shortestDistance) // If any of the enemies is closer than the original, make this distance the new shortestDistance and the new enemy to the nearestEnemy.
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}
if (nearestEnemy != null && shortestDistance <= range) // Sets the target to the nearestEnemy (only if its in range and not null).
{
target = nearestEnemy.transform;
targetEnemy = nearestEnemy.GetComponent<Enemy>();
}
else
{
target = null;
}
}
void Update()
{
if (target == null) // If there is no target, do nothing.
{
if (useLaser)
{
if (lineRenderer.enabled)
{
lineRenderer.enabled = false;
impactEffect.Stop();
impactLight.enabled = false;
audioSource.Stop();
}
}
return;
}
LockOnTarget();
if (useLaser)
{
Laser();
}
else
{
if (fireCountdown <= 0f)
{
Shoot();
fireCountdown = 1f / fireRate;
}
fireCountdown -= Time.deltaTime;
}
}
void Laser()
{
targetEnemy.TakeDamage(damageOverTime * Time.deltaTime);
targetEnemy.Slow(slowAmount);
if (!lineRenderer.enabled)
{
lineRenderer.enabled = true;
impactEffect.Play();
impactLight.enabled = true;
if (audioSource.isPlaying == false)
{
audioSource.Play();
}
}
lineRenderer.SetPosition(0, firePoint.position);
lineRenderer.SetPosition(1, target.position);
Vector3 dir = firePoint.position - target.position;
impactEffect.transform.position = target.position + dir.normalized * 1f;
impactEffect.transform.rotation = Quaternion.LookRotation(dir);
}
void LockOnTarget()
{
Vector3 dir = target.position - transform.position; // Store the direction from turret to target.
Quaternion lookRotation = Quaternion.LookRotation(dir); // I have no idea how this works...
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles; // Convert quaternion angles to euler angles and Lerp it (smoothing out the transition).
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f); // Only rotate around the y-axis.
}
void Shoot()
{
UnityEngine.GameObject bulletGO = (UnityEngine.GameObject)Instantiate(bulletPrefab, firePoint.position, firePoint.rotation); // Spawn a bullet at the location and rotation of firePoint. (Also makes this a GO to reference it.
Bullet bullet = bulletGO.GetComponent<Bullet>(); // I have no idea how this works...
audioSource.PlayOneShot(shootingSound, 0.2f);
if (bullet != null) // If there is a bullet, use the seek method from the bullet script.
{
bullet.Seek(target);
}
}
void OnDrawGizmosSelected() // Do this method if gizmo is selected.
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, range); // Draw a wire sphere on the selected point (selected turret f. e.) and give it the towers range.
}
}
The problem was that i had a script called "GameObject" in my Unity Project.
I was also able to rename all "UnityEngine.GameObject" to "Gameobject" by using the Quick Action in Visual Studio.
I am messing around in Unity and wanted to make a mechanic where a box would touch another object and then that object would follow the Player.
I have Cube set up like this:
And a Sphere with a Box Collider with same options.
My Player script is thus:
public class Player : MonoBehaviour {
public float speed = 0.0f;
public float moveX = 0.0f;
public float moveY = 0.0f;
public GameObject player;
public GameObject obj;
//public float force = 0.0f;
private bool collided = false;
// Use this for initialization
void Start () {
player = GameObject.FindWithTag ("Player");
}
// Update is called once per frame
void FixedUpdate () {
moveX = Input.GetAxis ("Horizontal");
moveY = Input.GetAxis ("Vertical");
player.GetComponent<Rigidbody> ().velocity = new Vector2 (moveX * speed, moveY * speed);
}
void OnCollisionEnter (Collision col) {
if (col.gameObject == obj) {
collided = true;
}
}
void OnCollisionExit (Collision col) {
if (col.gameObject == obj) {
collided = false;
}
}
void Update () {
if(collided) {
obj.transform.position = (player.transform.position - obj.transform.position)*speed;
}
}
}
What have I yet to do? Hoping someone can nudge me in the right direction.
I will provide you two scripts.
1st Script is FollowTarget. This will follow your target forcely.
2nd Script is SmoothFollow which will follow your target in a smooth movement.
FollowTarget.cs
using System;
using UnityEngine;
public class FollowTarget : MonoBehaviour
{
public Transform target;
public Vector3 offset = new Vector3(0f, 7.5f, 0f);
private void LateUpdate()
{
transform.position = target.position + offset;
}
}
SmoothFollow.cs
using UnityEngine;
public class SmoothFollow : MonoBehaviour
{
// The target we are following
[SerializeField]
private Transform target;
// The distance in the x-z plane to the target
[SerializeField]
private float distance = 10.0f;
// the height we want the camera to be above the target
[SerializeField]
private float height = 5.0f;
[SerializeField]
private float rotationDamping;
[SerializeField]
private float heightDamping;
// Use this for initialization
void Start() { }
// Update is called once per frame
void LateUpdate()
{
// Early out if we don't have a target
if (!target)
return;
// Calculate the current rotation angles
var wantedRotationAngle = target.eulerAngles.y;
var wantedHeight = target.position.y + height;
var currentRotationAngle = transform.eulerAngles.y;
var currentHeight = transform.position.y;
// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
transform.position = new Vector3(transform.position.x ,currentHeight , transform.position.z);
// Always look at the target
transform.LookAt(target);
}
}
Just choose one of them and then attach it to the gameObject. Like another box that is suppose to follow.
Remove your Update() function in your script as you don't need it anymore.
Also Remove your OnCollisionExit()
void OnCollisionEnter (Collision col) {
if (col.gameObject == obj) {
// If you choose to use SmoothFollow Uncomment this.
//col.GetComponent<SmoothFollow>().target = this.transform;
// If you choose to use FollowTarget Uncomment this
//col.GetComponent<FollowTarget>().target = this.transform;
}
}
I'm trying to find a way to pause my game in Unity without using "Time.timeScale = 0;". The reason I want to change this is that I want to make the character play an animation while the game is paused. Is there a way to change this script so that the gravity and forward speed only "sets in" after the player have clicked space? Or is there a better way to solve the problem?
This is the script:
public class PlayerMove : MonoBehaviour {
Vector3 velocity = Vector3.zero;
public Vector3 gravity;
public Vector3 FlyVelocity;
public float maxSpeed = 5f;
public float forwardSpeed = 1f;
bool didFly = false;
bool dead = false;
float deathCooldown;
Animator animator;
// Use this for initialization
void Start () {
animator = GetComponentInChildren<Animator>();
}
// Do Graphic & Input updates here
void Update(){
if (dead) {
deathCooldown -= Time.deltaTime;
if (deathCooldown <= 0) {
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0) ) {
Application.LoadLevel( Application.loadedLevel );
}
}
}
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0) ) {
didFly = true;
animator.SetTrigger ("DoFly");
}
}
void OnCollisionEnter2D(Collision2D collision) {
animator.SetTrigger ("Death");
dead = true;
}
// Do physics engine updates here
void FixedUpdate () {
if (dead)
return;
velocity += gravity * Time.deltaTime;
velocity.x = forwardSpeed;
if(didFly == true) {
didFly = false;
velocity += FlyVelocity;
}
velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
transform.position += velocity * Time.deltaTime;
deathCooldown = 0.5f;
}
}
If you are using Mechanim you could update animation state from script using Animator.Update even while actual time scale is zero.
Not sure if the trick is possible with legacy animation.