how to shoot in the mouse pointer angle? - c#

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.

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

unity projectile spawns but doesn't pick up velocity?

This is my code does anyone know or can anyone spot why my projectile remains stationary once it's spawned in? the projectile is the prefab shell thanks for your help in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TankBehaviour : MonoBehaviour
{
public GameObject shellPrefab;
public Transform fireTransform;
private bool isFired = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
transform.position += transform.forward * y;
transform.Rotate(0, x, 0);
if (Input.GetKeyUp(KeyCode.Space) && !isFired)
{
Debug.Log("fire!");
Fire();
}
}
void Fire()
{
//isFired = true;
GameObject shellInstance = Instantiate(shellPrefab,
fireTransform.position,
fireTransform.rotation) as GameObject;
if (shellInstance)
{
shellInstance.tag = "Shell";
Rigidbody shellRB = shellInstance.GetComponent<Rigidbody>();
shellRB.velocity = 15.0f * fireTransform.forward;
Debug.Log("velocity");
}
}
}
It is also generally discouraged to set the velocity of a rigidbody, but you can use the Rigidbody.AddForce() method to add force to a rigidbody. When you just want add force at the start, you can set the force mode in the function to impulse, like this rb.AddForce(Vector3.forward, ForceMode2D.Impulse);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TankBehaviour : MonoBehaviour
{
public GameObject shellPrefab;
public Transform fireTransform;
private bool isFired = false;
public float bulletSpeed;
void Update()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
transform.position += transform.forward * y;
transform.Rotate(0, x, 0);
if (Input.GetKeyUp(KeyCode.Space) && !isFired)
{
Debug.Log("fire!");
Fire();
}
}
void Fire()
{
//isFired = true;
GameObject shellInstance = Instantiate(shellPrefab, fireTransform.position, fireTransform.rotation) as GameObject;
if (shellInstance)
{
shellInstance.tag = "Shell";
Rigidbody shellRB = shellInstance.GetComponent<Rigidbody>();
shellRB.AddForce(15f * transform.forward, ForceMode.Impulse);
Debug.Log("velocity");
}
}
}
Hope this helps!

Switching camera to follow object in unity 3d

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;
}
}

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 get a projectile to shoot towards a gameobject

Im currently working on a TurretAi. I have it so that when the enemy is within a certain range the turret targets the enemy but I'm unable to get the turret to shoot the projectiles toward the enemy. this is currently what i have this is turret class.
using UnityEngine;
using System.Collections;
public class Defence : MonoBehaviour {
public float DistanceFromCastle,CoolDown;
public GameObject enemy;
public GameObject Bullet;
public int protectionRadius,bulletSpeed;
// Use this for initialization
void Start ()
{
protectionRadius = 35;
bulletSpeed = 50;
CoolDown = 5;
}
// Update is called once per frame
void Update () {
enemy = GameObject.FindGameObjectWithTag("Enemy");
if(enemy != null)
{
DistanceFromCastle = Vector3.Distance(GameObject.FindGameObjectWithTag("Enemy").transform.position,GameObject.FindGameObjectWithTag("Defence").transform.position);
//print (DistanceFromCastle);
if(DistanceFromCastle <= protectionRadius)
{
attackEnemy();
}
}
}
void attackEnemy()
{
transform.LookAt(enemy.transform);
CoolDown -= Time.deltaTime;
if (CoolDown <= 0)
{
Debug.DrawLine(transform.position,enemy.transform.position,Color.red);
Instantiate(Bullet,Vector3.forward,Quaternion.identity);
print("attack Enemy");
CoolDown = 5;
}
}
}
I also already have a cool down var so that it only shoot every 5 second any help would be awesome.
You were fairly close, you need to change this line:
Instantiate(Bullet, Vector3.forward, Quaternion.identity);
To this:
private const int SPAWN_DISTANCE = 5;
Instantiate(Bullet, transform.position + SPAWN_DISTANCE * transform.forward, transform.rotation);
Quaternion.identity refers to:
This quaternion corresponds to "no rotation".

Categories