I have a problem that main camera position doesn't change after CharacterController.SimpleMove() called. The task is to create scene where camera moves.
I have Main Camera game object with Character Controller and Script attached.
The issue is that nothing in vrCamera position changed after SimpleMove() called.
My question is what is wrong in this code. I suggest something wrong with binding between MainCamera object and CharacterController component, but I have spend a lot of time investigating and nothing working found.
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class VRLookWalk : MonoBehaviour {
public Transform vrCamera;
public float toggleAngle = 30.0f;
public float speed = 3.0f;
public bool moveForwad;
private CharacterController cc;
// Use this for initialization
void Start () {
cc = vrCamera.GetComponent<CharacterController>();
}
// Update is called once per frame
void Update () {
if (vrCamera.eulerAngles.x >= toggleAngle && vrCamera.eulerAngles.x < 90.0f)
{
Vector3 forward = vrCamera.TransformDirection(Vector3.forward);
cc.SimpleMove(forward * speed);
}
}
}
You can't move the VR Camera, it's the SDK that determine the mainCamera position.
In order to move your camera you can just make a new GameObject as a parent of your mainCamera then move the parent GameObject
Try this. Your TransformDirection probably returns wrong vector.
Vector3 forward = vrCamera.transform.forward;
cc.SimpleMove(forward * speed);
Related
I am having trouble getting the enemy's projectile to fly from the enemy to the player's position. When I play the game, the enemy bullet projectiles fly off in one direction on the screen and not toward the player. I think the issue might be in how I am assigning direction to the projectile prefab? Any suggestions would be much appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public float speed;
public Rigidbody enemyRb;
[SerializeField] float rateOfFire;
private GameObject player;
public GameObject projectilePrefab;
float nextFireAllowed;
public bool canFire;
Transform enemyMuzzle;
void Awake()
{
enemyRb = GetComponent<Rigidbody>();
player = GameObject.Find("Player");
enemyMuzzle = transform.Find("EnemyMuzzle");
}
void Update()
{
//move enemy rigidbody toward player
Vector3 lookDirection = (player.transform.position - transform.position).normalized;
enemyRb.AddForce(lookDirection * speed);
//overallSpeed
Vector3 horizontalVelocity = enemyRb.velocity;
horizontalVelocity = new Vector3(enemyRb.velocity.x, 0, enemyRb.velocity.z);
// turns enemy to look at player
transform.LookAt(player.transform);
//launches projectile toward player
projectilePrefab.transform.Translate(lookDirection * speed * Time.deltaTime);
Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
}
public virtual void Fire()
{
canFire = false;
if (Time.time < nextFireAllowed)
return;
nextFireAllowed = Time.time + rateOfFire;
//instantiate the projectile;
Instantiate(projectilePrefab, enemyMuzzle.position, enemyMuzzle.rotation);
canFire = true;
}
}
It looks like what is actually happening is that you create a bunch of bullets but don't store a reference to them. So each bullets sits in one place while the enemy moves closer to the player ( which might give the appearance that the bullets are moving relative to the enemy. ) I also assume the enemy is moving very fast since it is not scaled by delta time but is being updated every frame.
I think projectilePrefab is just the template object you're spawning, so you probably don't want to move it directly and you certainly don't want to instantiate a new bullet every frame.
If you want to move the object you spawned the least changes ( but still problematic ) from your example code might be:
public class EnemyController : MonoBehaviour
{
// add a reference
private GameObject projectileGameObject = null;
void Update()
{
//Update position of spawned projectile rather than the template
if(projectileGameObject != null ) {
projectileGameObject.transform.Translate(lookDirection * speed * Time.deltaTime);
}
// Be sure to remove this extra instantiate
//Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
}
public virtual void Fire()
{
//instantiate the projectile
projectileGameObject = Instantiate(projectilePrefab, enemyMuzzle.position, enemyMuzzle.rotation);
}
}
Or keep multiple bullets in a list. This implementation has the bug that it will always use the current enemy to player vector as the direction rather than the direction that existed when it was fired.
What you will probably want eventually is that each projectile is has it's own class script to handle projectile logic. All the enemyController class has to do is spawn the projectile and sets it's direction and position on a separate monobehavior that lives on the Projectile objects that handles it's own updates.
As you can see in the screenshoot I can't see prefabs in the game tab but only in the editor. I have made a simple function for shooting(not finished yet), it works fine, it spawns the prefabs but i can't see them in the game tab, I have already tried changing the Sorting Layer, move the camera, change Z position but nothing appen.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
[SerializeField]
float delayBetweenShots = 0.4f;
float timePassedSinceLast = 0f;
// Start is called before the first frame update
void Start()
{
timePassedSinceLast = delayBetweenShots;
}
// Update is called once per frame
void Update()
{
Aiming();
Shooting();
}
void Aiming()
{
var objectPos = Camera.main.WorldToScreenPoint(transform.position);
var dir = Input.mousePosition - objectPos;
transform.rotation = Quaternion.Euler(new Vector3(0,0,Mathf.Atan2(-dir.x, dir.y) * Mathf.Rad2Deg));
}
void Shooting()
{
if(Input.GetMouseButton(0) && timePassedSinceLast >= delayBetweenShots)
{
GameObject bullet = (GameObject)Instantiate(Resources.Load("bullet"), transform.position, transform.rotation);
timePassedSinceLast = 0f;
}
else
{
timePassedSinceLast += Time.deltaTime;
}
}
}
The prefabs get instantiated correctly. As others suggested as well, the best way to find "lost" objects in your game is to shoot some stuff, pause the game, go into scene view, turn on 3D mode and double click one of the prefabs in the hierarchy. The camera will take you straight to your object.
So I'm using the FPS Controller prefab from the standard asset and I've attached my script "Camera Push Up Effect" to the main camera(FirstPersonCharacter). Everything is working as it should but the problem that I'm currently having is whenever the player shoot, it doesn't push the camera upwards. What I'm trying to accomplish here is to give some recoil to the player's gun so that it does not stay in one place when the player shoots. I also want to limit the player rotation on the x-axis so that the gun doesn't keep going up forever(the min would be -90 degrees and the max would be 0).
using UnityEngine;
using InControl;
public class CameraPushUpEffect : MonoBehaviour
{
public float rotateSpeed;
public float maxRotationX;
public float minRotationX;
private Vector3 V3Rotate = Vector3.zero;
// Update is called once per frame
void Update ()
{
InputDevice device = InputManager.ActiveDevice;
if(device.RightBumper) // The player is shooting.
{
pushCameraUp();
}
else if (transform.localRotation.x != 0) // Slerp back to the original unrotated position.
{
transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.identity,
Time.deltaTime * rotateSpeed);
}
}
private void pushCameraUp()
{
V3Rotate.x += rotateSpeed * Time.deltaTime;
float newRotationX = Mathf.Clamp(V3Rotate.x, minRotationX, maxRotationX);
Quaternion maxRotation = Quaternion.Euler(newRotationX, 0, 0);
transform.localRotation = Quaternion.Slerp(transform.localRotation, maxRotation, Time.deltaTime * rotateSpeed);
}
}
It would appear it to be that the main culprit is the mouse look script in The First Person Controller script(This script is part of the FPSController prefab). Note the unity that I'm using has mouse look without extending MonoBehaviour and is set as private serializeable. The post in which I found my answer mentioned that it is not possible to rotate your camera(X-Axis) if the mouse look component is attached to the main camera which is clearly not the case(FPSController is the parent of the child FirstPersonCharacter which is tagged as the main camera and FirstPersonCharacter does not have mouse look attached to it). So I simply disabled the First Person Controller script to confirm if this was true and indeed it was.
Here is the link in case others would like to take a look at it as well.
Help with Recoil for guns
So I have an assignment that I have to do for school where an enemy shoots at the player in a gun type game. I have read about the LookAt() function in the Unity tutorials and used it to my knowledge of it. However it doesn't seem to be working. The following code is what I have so far:
public class EnemyControl : MonoBehaviour {
private Rigidbody rb;
public GameObject Bullet_Emitter2;
public GameObject EnemyBullet;
public float speedOfBullet;
private int score;
public Text countText;
public Text winText;
private GameObject Temporart_Bullet_Handler2;
public Transform player;
public Transform enemy;
void Start()
{
rb = GetComponent<Rigidbody>();
score = 0;
}
private void Update()
{
enemy.LookAt(player);
}
// Update is called once per frame
void FixedUpdate () {
int fire = Random.Range(0, 100);
if(fire == 0 || fire == 1 || fire == 5)
{
Temporart_Bullet_Handler2 = Instantiate(EnemyBullet, Bullet_Emitter2.transform.position, Bullet_Emitter2.transform.rotation) as GameObject;
Temporart_Bullet_Handler2.transform.Rotate(Vector3.right * 90);
Rigidbody Temporary_Rigid_Body;
Temporary_Rigid_Body = Temporart_Bullet_Handler2.GetComponent<Rigidbody>();
Temporary_Rigid_Body.AddForce(transform.up * speedOfBullet);
Destroy(Temporart_Bullet_Handler2, 20.0f);
}
}
}
The problem is my enemy now just looks at the ground instead of me and then just shoots downwards. Is there a way I can fix this? I have attached an image of what it looks like to a player playing the game?
Before putting in the LookAt() function my spaceman would just be stationary and fire bullets in a straight line but I need the AI to track the player instead of stationary. Is there another way to do this without using LookAt() or am I using this function wrong?
Thanks for the help in advance?
I would post this in comments but I can't yet because of low reputation
As Serlite pointed out, LookAt() only faces the GameObject's trasnform.forward (which is desired to be (0, 0, 1) when the object is not rotated) towards the target passed as argument.
To 'fix' this simply add an empty GameObject to your Hirarchy and set your AI object as its child
Empty GameObject
- AI GameObject (with your script)
Now you can set a global rotation for your object (Rotate the parent) in a way that the AI's forwards faces z+.
When reading this, keep in mind I'm new to both programming and Unity, so I might be missing some terms or tools Unity offer. Please elaborate your answers in an ELI5 manner. Thanks in advance!
I am currently working on some game-physics for a small personal project. Currently I've created a platform, a character and what should be, a following companion.
However, since I'm still not on a level, where I can create perfect code on own hand, I found an "enemy" script and tried to modify it a bit.
It Works to an extend, but it needs some tweaks which I hope I can help aquire with you guys.
This is how it looks now (the orange square is the companion)
It follows the player, and I can tweak the speed to fit as a companion, and not a player. However, as the Picture presents, the companion runs for the center of the player. What I want to create is a companion which follows the player, but still keeps a small gap from the player.
My first thoughts was to create some kind of permanent offset, but I fail to figure out how to do this without messing up the follow function.
I hope you can help me, it will be much appreciated!
Here's the code for reference.
Code attached to Player:
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
//In the editor, add your wayPoint gameobject to the script.
public GameObject wayPoint;
//This is how often your waypoint's position will update to the player's position
private float timer = 0.5f;
void Update ()
{
if (timer > 0) {
timer -= Time.deltaTime;
}
if (timer <= 0) {
//The position of the waypoint will update to the player's position
UpdatePosition ();
timer = 0.5f;
}
}
void UpdatePosition ()
{
//The wayPoint's position will now be the player's current position.
wayPoint.transform.position = transform.position;
}
}
Code attached to companion:
using UnityEngine;
using System.Collections;
public class FollowerOffset : MonoBehaviour {
//You may consider adding a rigid body to the zombie for accurate physics simulation
private GameObject wayPoint;
private Vector3 wayPointPos;
//This will be the zombie's speed. Adjust as necessary.
private float speed = 10.0f;
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
}
void Update ()
{
wayPointPos = new Vector3(wayPoint.transform.position.x, transform.position.y, wayPoint.transform.position.z);
//Here, the zombie's will follow the waypoint.
transform.position = Vector3.MoveTowards(transform.position, wayPointPos, speed * Time.deltaTime);
}
}
bump, I guess ? :)
You can use smooth follow script. I have created a sample class for you. This class has features to follow any given gameobject with some delay and offset. You will have to tweak some values according to your need.
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
[SerializeField]
private GameObject wayPoint;
[SerializeField]
public Vector3 offset;
public Vector3 targetPos;//Edit: I forgot to declare this on firt time
public float interpVelocity;
public float cameraLerpTime = .1f;
public float followStrength = 15f;
// Use this for initialization
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
offset = new Vector3 (5,0,0);//input amount of offset you need
}
void FixedUpdate () {
if (wayPoint) {
Vector3 posNoZ = transform.position;
Vector3 targetDirection = (wayPoint.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * followStrength;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp (transform.position, targetPos + offset, cameraLerpTime);
}
}
}
Attach this class to your player companion, play with different values.
To preserve object orientation your companion schould not be anyways child of your main character.
Your wayPoint doesn't needs to be a GameObject but a Transform instead and your code will looks like better.
If your game is a 2D platform your and your companion needs to be backwards your player it probabli applys to just one axis (X?) so you can decrement your waiPoint in a more directly way by calculating it on your UpdatePosition function like this:
wayPoint.position = transform.position * (Vector3.left * distance);
where your "distance" could be a public float to easily setup.
so on your companion script Update just do:
transform.position = Vector3.MoveTowards(transform.position, wayPoint.position, speed * Time.deltaTime);
I can't test it right now so you could have problems with Vector3 multiply operations, just comment and I'll try to fix as possible ;)