Switching camera to follow object in unity 3d - c#

I'm trying to switch one camera to another to follow the sphere. What's happening in my script is, at first the main camera focuses the ball and as soon as it is grabbed and thrown, the main camera is switched off or disabled and the second camera is enabled to follow the ball when it is in motion. But the second camera doesn't follow in the direction of the ball. Below is the scripts that i implemented.
Note:- I'm attaching the second camera script at run time to second camera.
PickupObject.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pickupobject : MonoBehaviour
{
GameObject mainCamera;
//public GameObject empty;
bool carrying;
public GameObject carriedObject;
// Camera cam;
public float distances;
public float smooth;
float speed = 1000f;
private Vector3 offset;
public Camera camera;
private MovingBall script;
// Use this for initialization
void Start()
{
//cam = GameObject.Find("MainCamera").GetComponent<Camera>();
mainCamera = GameObject.FindWithTag("MainCamera");
camera = GameObject.FindWithTag("secondCamera").GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.T) && carrying)
{
carrying = !carrying;
ThrowBall();
}
if (carrying)
{
carry(carriedObject);
// CheckDrop();
}
else
{
pickup();
}
}
private void pickup()
{
if (Input.GetKeyDown(KeyCode.E))
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
pickupable p = hit.collider.GetComponent<pickupable>();
if (p != null)
{
carrying = true;
carriedObject = p.gameObject;
camera.enabled = true;
camera.gameObject.AddComponent<CameraController>();
carriedObject.AddComponent<MovingBall>();
}
}
}
}
void carry(GameObject o)
{
o.GetComponent<Rigidbody>().isKinematic = true;
o.transform.position = mainCamera.transform.position + mainCamera.transform.forward * distances;
}
//void CheckDrop()
//{
// if (Input.GetKeyDown(KeyCode.U))
// {
// Drop();
// }
//}
//void Drop()
//{
// ThrowBall();
//}
void ThrowBall()
{
mainCamera.SetActive(false);
carriedObject.GetComponent<Rigidbody>().isKinematic = false;
carriedObject.GetComponent<Rigidbody>().AddForce(0f, 0f, speed);
}
}
CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
// Use this for initialization
public GameObject icosphere;
private Vector3 offset;
pickupobject ball = new pickupobject();
void Start () {
ball.camera = GameObject.FindWithTag("secondCamera").GetComponent<Camera>();
//offset = transform.position - icosphere.transform.position;
//icosphere = GameObject.FindWithTag("yellowball");
// icosphere = ball.carriedObject.GetComponent<GameObject>();
offset = ball.camera.transform.position - GameObject.FindWithTag("purpleball").transform.position;
}
// Update is called once per frame
void LateUpdate () {
ball.camera.transform.position = GameObject.FindWithTag("purpleball").transform.position + offset;
// transform.position = ball.carriedObject.GetComponent<GameObject>().transform.position + offset;
}
}

Related

transform.Rotate an empty game object in unity

I am trying to make an empty game object which is the path generator rotate when placing a tile left or right.
But somehow it does not rotate the object.
Plz help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathGenerator : MonoBehaviour
{
#region Settings
//Settings to customize this script
float gapSize = 0.4f; //0,4 coord gaps between squares
#endregion
public GameObject ChosenPath;
public GameObject NonChosenPath;
private Vector3 InitPos;
private Vector3 NextPos;
public Vector3 angleRotation;
public string pathDirection;
// Start is called before the first frame update
void Start()
{
InitPos = new Vector2(gapSize,gapSize);
NextPos = InitPos;
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.Space))
{
ChangePath();
}
}
void ChangePath()
{
double randomNumQ = Random.Range(0,3);
if(randomNumQ == 0)
{
pathDirection = "Forward";
NextPos.y += gapSize;
}
else if(randomNumQ == 1)
{
pathDirection = "Left";
NextPos.x += gapSize;
angleRotation.z = -90;
transform.Rotate(angleRotation);
}
else if(randomNumQ == 2)
{
pathDirection = "Right";
NextPos.x -= gapSize;
angleRotation.z = 90;
transform.Rotate(angleRotation);
}
Instantiate(ChosenPath, NextPos, transform.rotation = Quaternion.identity);
transform.position = NextPos;
}
}
Actually the problem was that the Instantiate was after and it resets the rotation of the object

Cube Translation

I can't understand why my cube won't to translate in the fineMovimento (endMovement) vector3 position along Z.
Here the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovimentoPorta : MonoBehaviour {
public Transform target;
Vector3 fineMovimento = new Vector3(221.04f, -8.98f,329);
void Update () {
if (Input.GetKeyDown(KeyCode.P))
{
while (target.position != fineMovimento)
{
target.Translate (Vector3.forward*10.0f*Time.deltaTime); //il cubo si doverbbe muovere lungo l'asse Z +
}
}
}
}
Don't use while(...) in void Update() for translate (Because Unity hangs when you press P in play mode). If you want to move to fineMovimento smoothly, one way is to use Vector3.Lerp().
Try this:
public Transform target;
Vector3 fineMovimento;
float smoothTime = 0.125f;
void Start()
{
fineMovimento = target.position; // Initialize
}
void Update ()
{
target.position = Vector3.Lerp(target.position, fineMovimento, smoothTime);
if (Input.GetKeyDown(KeyCode.P))
{
fineMovimento = new Vector3(221.04f, -8.98f,329); // Set end position
}
}
Hope this what you want.

Transform instantiated bullet towards camera center

I have made a very simple gun script, currently the bullet transform in the same direction as the GameObject i have set as the bullet spawn position. but i want the bullet to transform towards the center of the camera, i have a couple of different ideas. The 1st one is shooting a raycast when the raycast hit something transform the bullet form bulletpos to raycasthit position. But i dont quite know how to do this, can anyone help me?
Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour {
public Transform bulletCapTransform;
public GameObject bulletCap;
public float ammo;
public float magAmmo;
public GameObject shootEffect;
public Transform bulletTransform;
public GameObject bullet;
public float bulletForce;
public GameObject crossHair;
public float fireRate = 0.3333f;
private float timeStamp;
Animator anim;
// Use this for initialization
void Start ()
{
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update ()
{
Shoot();
Aim();
}
public void OnGUI()
{
GUI.Box(new Rect(10, 10, 50, 25), magAmmo + " / " + ammo);
}
public void Shoot()
{
if(Time.time >= timeStamp && Input.GetButton("Fire1") && magAmmo > 0)
{
GameObject bulletCapInstance;
bulletCapInstance = Instantiate(bulletCap, bulletCapTransform.transform.position, bulletCapTransform.rotation) as GameObject;
bulletCapInstance.GetComponent<Rigidbody>().AddForce(bulletCapTransform.right *10000);
GameObject bulletInstance;
bulletInstance = Instantiate(bullet, bulletTransform) as GameObject;
bulletInstance.GetComponent<Rigidbody>().AddForce(bulletTransform.forward * bulletForce);
Instantiate(shootEffect, bulletTransform);
timeStamp = Time.time + fireRate;
magAmmo = magAmmo -1;
}
if(Input.GetKeyDown(KeyCode.R))
{
//This is just for testing
magAmmo = magAmmo + 10;
}
}
void Aim()
{
if(Input.GetButton("Fire2"))
{
anim.SetBool("Aiming", true);
crossHair.SetActive(false);
}
else
{
anim.SetBool("Aiming", false);
crossHair.SetActive(true);
}
}
}
So i think you want to fire a projectile from a "gun" object towards whatever is at the centre of your screen (regardless of central objects distance)
This script is working for me and shoots dead into the centre of the view.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public Transform bulletCapTransform;
public GameObject bulletCap;
public float ammo;
public float magAmmo;
public GameObject shootEffect;
public Transform bulletTransform;
public GameObject bullet;
public float bulletForce;
public GameObject crossHair;
public float fireRate = 0.3333f;
private float timeStamp;
Animator anim;
// Use this for initialization
void Start()
{
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Shoot();
Aim();
}
public void OnGUI()
{
GUI.Box(new Rect(10, 10, 50, 25), magAmmo + " / " + ammo);
}
public void Shoot()
{
if (Time.time >= timeStamp && Input.GetButton("Fire1") && magAmmo > 0)
{
Debug.Log("shoot");
GameObject bulletCapInstance;
bulletCapInstance = Instantiate(bulletCap, bulletCapTransform.transform.position, bulletCapTransform.rotation) as GameObject;
bulletCapInstance.GetComponent<Rigidbody>().AddForce(bulletCapTransform.right * 10000);
//This will send a raycast straight forward from your camera centre.
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
//check for a hit
if (Physics.Raycast(ray, out hit))
{
// take the point of collision (make sure all objects have a collider)
Vector3 colisionPoint = hit.point;
//Create a vector for the path of the bullet from the 'gun' to the target
Vector3 bulletVector = colisionPoint - bullet.transform.position;
GameObject bulletInstance = Instantiate(bullet, bulletTransform) as GameObject;
//See it on it's way
bulletInstance.GetComponent<Rigidbody>().AddForce(bulletVector * bulletForce);
}
Instantiate(shootEffect, bulletTransform);
timeStamp = Time.time + fireRate;
magAmmo = magAmmo - 1;
}
if (Input.GetKeyDown(KeyCode.R))
{
//This is just for testing
magAmmo = magAmmo + 10;
}
}
void Aim()
{
if (Input.GetButton("Fire2"))
{
anim.SetBool("Aiming", true);
crossHair.SetActive(false);
}
else
{
anim.SetBool("Aiming", false);
crossHair.SetActive(true);
}
}
}
The crucial point to remember is this:
Camera.main.ViewportPointToRay(0.5, 0.5, 0);
Will shoot a raycast dead ahead from the centre of your screen.
It's worth really getting to know raycasting and it's ins and outs. it seems daunting at first but its so useful once you've got it down and it's pretty intuitive. There are a lot of good youtube tutorials.
Hope your game turns out good!

How to make enemies turn and move towards player when near? Unity3D

I am trying to make my enemy object turn and start moving towards my player object when the player comes within a certain vicinity.
For the turning I have been testing the transform.LookAt() function although it isn't returning the desired results as when the player is too close to the enemy object the enemy starts to tilt backwards and I only want my enemy to be able to rotate along the y axis, thanks in advance.
using UnityEngine;
using System.Collections;
public class EnemyController : MonoBehaviour {
public Transform visionPoint;
private PlayerController player;
public Transform Player;
public float visionAngle = 30f;
public float visionDistance = 10f;
public float moveSpeed = 2f;
public float chaseDistance = 3f;
private Vector3? lastKnownPlayerPosition;
// Use this for initialization
void Start () {
player = GameObject.FindObjectOfType<PlayerController> ();
}
// Update is called once per frame
void Update () {
// Not giving the desired results
transform.LookAt(Player);
}
void FixedUpdate () {
}
void Look () {
Vector3 deltaToPlayer = player.transform.position - visionPoint.position;
Vector3 directionToPlayer = deltaToPlayer.normalized;
float dot = Vector3.Dot (transform.forward, directionToPlayer);
if (dot < 0) {
return;
}
float distanceToPlayer = directionToPlayer.magnitude;
if (distanceToPlayer > visionDistance)
{
return;
}
float angle = Vector3.Angle (transform.forward, directionToPlayer);
if(angle > visionAngle)
{
return;
}
RaycastHit hit;
if(Physics.Raycast(transform.position, directionToPlayer, out hit, visionDistance))
{
if (hit.collider.gameObject == player.gameObject)
{
lastKnownPlayerPosition = player.transform.position;
}
}
}
}
change the look at target:
void Update () {
Vector3 lookAt = Player.position;
lookAt.y = transform.position.y;
transform.LookAt(lookAt);
}
this way the look at target will be on the same height as your object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyMovement : MonoBehaviour
{
public Transform Player;
public float MoveSpeed = 4;
int MaxDist = 10;
int MinDist = 5;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
// Put what do you want to happen here
}
}
}
}

how to shoot in the mouse pointer angle?

I have a player which is shooting with bullets to the enemy,the bullets are moving towards the right,in a correct angle,but my bullet is not pointing towards that angle,the bullets is unable to change its angle.,how to change it?,it should not only move in that angle but also point towards it,currently i am transforming it to right of the screen.,the enemy are spawning from the right.here is my code for movement and transformation,any help thanx,
this is the code for direction,and for the shooting rate
using UnityEngine;
using System.Collections;
public class WeaponScript : MonoBehaviour
{
public Transform shotPrefab;
public float shootingRate = 0.25f;
private float shootCooldown;
void Start()
{
shootCooldown = 0f;
}
void Update()
{
if (shootCooldown > 0)
{
shootCooldown -= Time.deltaTime;
}
}
public void Attack(bool isEnemy)
{
if (CanAttack)
{
shootCooldown = shootingRate;
// Create a new shot
var shotTransform = Instantiate(shotPrefab) as Transform;
// Assign position
shotTransform.position = transform.position;
// The is enemy property
ShotScript shot = shotTransform.gameObject.GetComponent<ShotScript>();
if (shot != null)
{
shot.isEnemyShot = isEnemy;
}
// Make the weapon shot always towards it
MoveScript move = shotTransform.gameObject.GetComponent<MoveScript>();
if (move != null)
{
move.direction = this.transform.right;
}
}
}
public bool CanAttack
{
get
{
return shootCooldown <= 0f;
}
}
}
this is the code for movement
using UnityEngine;
using System.Collections;
public class MoveScript : MonoBehaviour {
public Vector2 speed = new Vector2(10,10);
public Vector2 direction = new Vector2(1,0);
void Update () {
Vector3 movement = new Vector3 (speed.x * direction.x, speed.y * direction.y, 0);
movement *= Time.deltaTime;
transform.Translate(movement);
}
}
Using transform.LookAt(transform.position + direction) will immediately point your object in the specified direction.

Categories