Drag 2 GameObjects simultaneously in Unity 2018 - c#

I wanna to Drag two gameObjects simultaneously in Y-Axis so I have made this code but actually, It's just working for one gameObject to drag
I have tested a lot of ways to do that but I couldn't
Can you guys help me to do this?
Thanks a lot
Here's my code:
using UnityEngine;
using System.Collections;
public class Drag2 : MonoBehaviour
{
private float dist;
private bool dragging = false;
private Vector3 offset;
private Transform toDrag;
void Update()
{
Vector3 v3;
if (Input.touchCount < 1)
{
dragging = false;
return;
}
Touch[] touch = Input.touches;
for (int i = 0; i < Input.touchCount; i++)
{
Vector3 pos = touch[i].position;
if (touch[i].phase == TouchPhase.Stationary)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(pos);
if (Physics.Raycast(ray, out hit) && (hit.collider.CompareTag("Object")))
{
Debug.Log(Input.touchCount);
toDrag = hit.transform;
dist = hit.transform.position.z - Camera.main.transform.position.z;
v3 = new Vector3(0, pos.y, dist);
v3 = Camera.main.ScreenToWorldPoint(v3);
offset = toDrag.position - v3;
dragging = true;
}
}
if (dragging && touch[i].phase == TouchPhase.Moved)
{
v3 = new Vector3(0, Input.mousePosition.y, dist);
v3 = Camera.main.ScreenToWorldPoint(v3);
toDrag.position = v3 + offset;
}
if (dragging && (touch[i].phase == TouchPhase.Ended || touch[i].phase == TouchPhase.Canceled))
{
dragging = false;
}
}
}
}

Related

Camera does not contain a definition for ViewportPointToRay

I'm trying to make a script that can shoot stuff but this line isn't working. I've googled the issue and even unity says that this is correct
using UnityEngine;
using TMPro;
public class ShootGun_Script : MonoBehaviour
{
public GameObject bullet;
public float shootForce, upwardForce;
public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
public int magazineSize, bulletsPerTap;
public bool allowButtonHold;
int bulletsLeft, bulletsShot;
public Rigidbody playerRb;
public float recoilForce;
bool shooting, readyToShoot, reloading;
public Camera fpsCam;
public Transform attackPoint;
public GameObject muzzleFlash;
public TextMeshProUGUI ammunitionDisplay;
public bool allowInvoke = true;
private void Awake()
{
bulletsLeft = magazineSize;
readyToShoot = true;
}
private void Update()
{
MyInput();
if (ammunitionDisplay != null)
ammunitionDisplay.SetText(bulletsLeft / bulletsPerTap + " / " + magazineSize / bulletsPerTap);
}
private void MyInput()
{
if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
else shooting = Input.GetKeyDown(KeyCode.Mouse0);
if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();
if (readyToShoot && shooting && !reloading && bulletsLeft > 0)
{
bulletsShot = 0;
Shoot();
}
}
private void Shoot()
{
readyToShoot = false;
** Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));**
RaycastHit hit;
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(75);
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0);
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
currentBullet.transform.forward = directionWithSpread.normalized;
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);
if (muzzleFlash != null)
Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);
bulletsLeft--;
bulletsShot++;
if (allowInvoke)
{
Invoke("ResetShot", timeBetweenShooting);
allowInvoke = false;
playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse);
}
if (bulletsShot < bulletsPerTap && bulletsLeft > 0)
Invoke("Shoot", timeBetweenShots);
}
private void ResetShot()
{
readyToShoot = true;
allowInvoke = true;
}
private void Reload()
{
reloading = true;
Invoke("ReloadFinished", reloadTime);
}
private void ReloadFinished()
{
bulletsLeft = magazineSize;
reloading = false;
}
}

How can i make object to rotate smooth towards a target with raycast?

I have object that move around in fixed radius around another object with random height.
In this script i want the transform(turret) to rotate facing the target(target is the object that move with the random height) and that the laser that shoot will hit all the time the moving around target.
In the original i used the mouse to rotate the transform to be facing objects but now i want that the transform will rotate automatic to the moving target with the laser.
I added this part to the script and the laser start when running the game but the transform is not rotating facing the target. and i still can rotate the transform with the mouse and in this case i don't want the mouse to rotate the transform but that the transform will be rotating automatic.
if (startLaser)
{
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
startLaser = false;
}
if (Cam != null)
{
RaycastHit hit;
RayMouse = Cam.ScreenPointToRay(target.position);
if(Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, MaxLength))
{
RotateToMouseDirection(gameObject, hit.point);
}
else
{
var pos = RayMouse.GetPoint(MaxLength);
RotateToMouseDirection(gameObject, pos);
}
}
but it's not working the transform is not rotating automatic and the mouse still controlling the rotating.
This is the full script :
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System;
using UnityEngine;
public class Hovl_DemoLasers : MonoBehaviour
{
public Transform target;
public GameObject FirePoint;
public Camera Cam;
public float MaxLength;
public GameObject[] Prefabs;
private Ray RayMouse;
private Vector3 direction;
private Quaternion rotation;
[Header("GUI")]
private float windowDpi;
private int Prefab;
private GameObject Instance;
private Hovl_Laser LaserScript;
private Hovl_Laser2 LaserScript2;
private bool rotateMouse = true;
private bool startLaser = true;
//Double-click protection
private float buttonSaver = 0f;
void Start ()
{
if (Screen.dpi < 1) windowDpi = 1;
if (Screen.dpi < 200) windowDpi = 1;
else windowDpi = Screen.dpi / 200f;
Counter(0);
}
void Update()
{
//Enable lazer
if (Input.GetMouseButtonDown(0))
{
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
rotateMouse = true;
}
if (Input.GetMouseButtonDown(1))
{
rotateMouse = false;
}
//To change lazers
if ((Input.GetKey(KeyCode.A) || Input.GetAxis("Horizontal") < 0) && buttonSaver >= 0.4f)// left button
{
buttonSaver = 0f;
Counter(-1);
}
if ((Input.GetKey(KeyCode.D) || Input.GetAxis("Horizontal") > 0) && buttonSaver >= 0.4f)// right button
{
buttonSaver = 0f;
Counter(+1);
}
buttonSaver += Time.deltaTime;
if (startLaser)
{
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
startLaser = false;
}
if (Cam != null)
{
RaycastHit hit;
RayMouse = Cam.ScreenPointToRay(target.position);
if(Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, MaxLength))
{
RotateToMouseDirection(gameObject, hit.point);
}
else
{
var pos = RayMouse.GetPoint(MaxLength);
RotateToMouseDirection(gameObject, pos);
}
}
//Current fire point
if (Cam != null && rotateMouse)
{
RaycastHit hit;
var mousePos = Input.mousePosition;
RayMouse = Cam.ScreenPointToRay(mousePos);
if (Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, MaxLength))
{
RotateToMouseDirection(gameObject, hit.point);
}
else
{
var pos = RayMouse.GetPoint(MaxLength);
RotateToMouseDirection(gameObject, pos);
}
}
else
{
Debug.Log("No camera");
}
}
//GUI Text
void OnGUI()
{
GUI.Label(new Rect(10 * windowDpi, 5 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use the keyboard buttons A/<- and D/-> to change lazers!");
GUI.Label(new Rect(10 * windowDpi, 20 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use left mouse button for shooting!");
}
//To change prefabs (count - prefab number)
void Counter(int count)
{
Prefab += count;
if (Prefab > Prefabs.Length - 1)
{
Prefab = 0;
}
else if (Prefab < 0)
{
Prefab = Prefabs.Length - 1;
}
}
//To rotate fire point
void RotateToMouseDirection (GameObject obj, Vector3 destination)
{
direction = destination - obj.transform.position;
rotation = Quaternion.LookRotation(direction);
obj.transform.localRotation = Quaternion.Lerp(obj.transform.rotation, rotation, 1);
}
}
This is working fine : I'm not sure if i need to use the out hit variable in the Automatic aiming part ? do i need to use the hit variable and if so how ?
// Automatic aiming part
if (Cam != null)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, MaxLength))
{
RotateToMouseDirection(gameObject, target.position);
}
}
Anyway it's not working as i wanted.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System;
using UnityEngine;
public class Hovl_DemoLasers : MonoBehaviour
{
public Transform target;
public GameObject FirePoint;
public Camera Cam;
public float MaxLength;
public GameObject[] Prefabs;
private Ray RayMouse;
private Ray AutomaticRay;
private Vector3 direction;
private Quaternion rotation;
[Header("GUI")]
private float windowDpi;
private int Prefab;
private GameObject Instance;
private Hovl_Laser LaserScript;
private Hovl_Laser2 LaserScript2;
private bool rotateMouse = true;
private bool startLaser = true;
//Double-click protection
private float buttonSaver = 0f;
void Start ()
{
//LaserEndPoint = new Vector3(0, 0, 0);
if (Screen.dpi < 1) windowDpi = 1;
if (Screen.dpi < 200) windowDpi = 1;
else windowDpi = Screen.dpi / 200f;
Counter(0);
}
void Update()
{
//Enable lazer
if (Input.GetMouseButtonDown(0))
{
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
rotateMouse = true;
}
if (Input.GetMouseButtonDown(1))
{
rotateMouse = false;
}
//Disable lazer prefab
if (Input.GetMouseButtonUp(0))
{
/*if (LaserScript) LaserScript.DisablePrepare();
if (LaserScript2) LaserScript2.DisablePrepare();
Destroy(Instance,1);*/
}
//To change lazers
if ((Input.GetKey(KeyCode.A) || Input.GetAxis("Horizontal") < 0) && buttonSaver >= 0.4f)// left button
{
buttonSaver = 0f;
Counter(-1);
}
if ((Input.GetKey(KeyCode.D) || Input.GetAxis("Horizontal") > 0) && buttonSaver >= 0.4f)// right button
{
buttonSaver = 0f;
Counter(+1);
}
buttonSaver += Time.deltaTime;
if (startLaser)
{
rotateMouse = false;
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
startLaser = false;
}
// Automatic aiming part
if (Cam != null)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, MaxLength))
{
RotateToMouseDirection(gameObject, target.position);
}
}
//Current fire point
if (Cam != null && rotateMouse)
{
RaycastHit hit; //DELATE THIS IF YOU WANT TO USE LASERS IN 2D
var mousePos = Input.mousePosition;
RayMouse = Cam.ScreenPointToRay(mousePos);
//ADD THIS IF YOU WANT TO USE LASERS IN 2D: RaycastHit2D hit = Physics2D.Raycast(RayMouse.origin, RayMouse.direction, MaxLength);
if (Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, MaxLength)) //CHANGE THIS IF YOU WANT TO USE LASERRS IN 2D: if (hit.collider != null)
{
RotateToMouseDirection(gameObject, hit.point);
}
else
{
var pos = RayMouse.GetPoint(MaxLength);
RotateToMouseDirection(gameObject, pos);
}
}
else
{
Debug.Log("No camera");
}
}
//GUI Text
void OnGUI()
{
GUI.Label(new Rect(10 * windowDpi, 5 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use the keyboard buttons A/<- and D/-> to change lazers!");
GUI.Label(new Rect(10 * windowDpi, 20 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use left mouse button for shooting!");
}
//To change prefabs (count - prefab number)
void Counter(int count)
{
Prefab += count;
if (Prefab > Prefabs.Length - 1)
{
Prefab = 0;
}
else if (Prefab < 0)
{
Prefab = Prefabs.Length - 1;
}
}
//To rotate fire point
void RotateToMouseDirection (GameObject obj, Vector3 destination)
{
direction = destination - obj.transform.position;
rotation = Quaternion.LookRotation(direction);
obj.transform.localRotation = Quaternion.Lerp(obj.transform.rotation, rotation, 1);
}
}

Grappling hook joint won't hook onto a game object Unity

I've started trying to code a grappling hook in unity but my distance joint won't hook onto the gameobject but rather blank space. I want to make it so that my distance joint will hook onto the gameobject instead of blank space. I feel that maybe there is a problem with the joint vectors but I don't know.
Here's my code:
public class Grapplescript : MonoBehaviour
{
public LineRenderer line;
DistanceJoint2D joint;
Vector3 targetPos;
RaycastHit2D hit;
public float distance = 10f;
public LayerMask mask;
public float step = 0.02f;
// Use this for initialization
void Start()
{
joint = GetComponent<DistanceJoint2D>();
joint.enabled = false;
line.enabled = false;
}
// Update is called once per frame
void Update()
{
if (joint.distance > .5f)
joint.distance -= step;
else
{
line.enabled = false;
joint.enabled = false;
}
if (Input.GetKeyDown(KeyCode.Mouse1))
{
targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPos.z = 0;
hit = Physics2D.Raycast(transform.position, targetPos - transform.position, distance, mask);
if (hit.collider != null && hit.collider.gameObject.GetComponent<Rigidbody2D>() != null)
{
joint.enabled = true;
// Debug.Log (hit.point - new Vector2(hit.collider.transform.position.x,hit.collider.transform.position.y);
Vector2 connectPoint = hit.point - new Vector2(hit.collider.transform.position.x, hit.collider.transform.position.y);
connectPoint.x = connectPoint.x / hit.collider.transform.localScale.x;
connectPoint.y = connectPoint.y / hit.collider.transform.localScale.y;
Debug.Log(connectPoint);
joint.connectedAnchor = connectPoint;
joint.connectedBody = hit.collider.gameObject.GetComponent<Rigidbody2D>();
// joint.connectedAnchor = hit.point - new Vector2(hit.collider.transform.position.x,hit.collider.transform.position.y);
joint.distance = Vector2.Distance(transform.position, hit.point);
line.enabled = true;
line.SetPosition(0, transform.position);
line.SetPosition(1, hit.point);
//reference to another code
line.GetComponent<roperatio>().grabPos = hit.point;
}
}
//line.SetPosition(1, joint.connectedBody.transform.TransformPoint(joint.connectedAnchor));
if (Input.GetKey(KeyCode.Mouse1))
{
line.SetPosition(0, transform.position);
}
if (Input.GetKeyUp(KeyCode.Mouse1))
{
joint.enabled = false;
line.enabled = false;
}
}
}

How to keep object rotating in direction of touch movement?

I am looking for following implementation in unity based touch game:
I need object to rotate with the touch so it can be viewed from all sides(As long as touch is moving)
The object should keep on rotating in direction of previous touch
movement (when touch ends)
I tried implementing below code. But rotation is quiet quirky. It sometime rotates too fast sometimes in opposite direction of the swipe etc.
Here is what i have tried:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Functionalities : MonoBehaviour
{
public GameObject m_objecttorotate;
Vector3 localAngle;
[SerializeField]
float rotateSpeed = 0.09f;
Touch touchZero;
Vector3 rotateAxis;
float newMouseYpos = 0;
float prevMouseYpos = 0;
bool isIncreasing;
bool isDecreasing;
bool rotateManually;
void Update()
{
if (Input.touchCount > 0)
{
touchZero = Input.GetTouch(0);
//Rotate the model based on offset
localAngle = m_objecttorotate.transform.localEulerAngles;
localAngle.y -= rotateSpeed * touchZero.deltaPosition.x;
m_objecttorotate.transform.localEulerAngles = localAngle;
if (touchZero.deltaPosition != Vector2.zero)
{
rotateAxis = touchZero.deltaPosition;
}
}
else
{
localAngle.y += rotateSpeed * rotateAxis.y;
m_objecttorotate.transform.localEulerAngles = localAngle;
}
CheckIfTouchIsMovingUpOrDown();
if (isIncreasing)
{
Vector3 newPos = new Vector3(m_objecttorotate.transform.position.x, -0.25f, m_objecttorotate.transform.position.z);
m_objecttorotate.transform.position = Vector3.Lerp(m_objecttorotate.transform.position, newPos, 1 * Time.deltaTime);
}
else if (isDecreasing)
{
Vector3 newPos = new Vector3(m_objecttorotate.transform.position.x, 0.25f, m_objecttorotate.transform.position.z);
m_objecttorotate.transform.position = Vector3.Lerp(m_objecttorotate.transform.position, newPos, 1 * Time.deltaTime);
}
else
{
Vector3 newPos = new Vector3(m_objecttorotate.transform.position.x, 0f, m_objecttorotate.transform.position.z);
m_objecttorotate.transform.position = Vector3.Lerp(m_objecttorotate.transform.position, newPos, 1 * Time.deltaTime);
}
}
void CheckIfTouchIsMovingUpOrDown()
{
if (Input.GetMouseButton(0))
{
if (prevMouseYpos != newMouseYpos)
{
if (prevMouseYpos < newMouseYpos + 1f)
{
isIncreasing = true;
isDecreasing = false;
Debug.Log("Increasing");
prevMouseYpos = newMouseYpos;
}
else if (prevMouseYpos > newMouseYpos - 1f)
{
isDecreasing = true;
isIncreasing = false;
Debug.Log("Decreasing");
prevMouseYpos = newMouseYpos;
}
}
newMouseYpos = Input.mousePosition.y;
}
else
{
//isDecreasing = false;
// isIncreasing = false;
prevMouseYpos = newMouseYpos;
}
}
}

Unity Player is shooting at himself

I have the following issue in my game:
There're two characters in the scene and they can shoot at each other. There is an empty game object attached in the front of each other called "SpawnBullet", which spawns the projectile, as you can see in the image.
The problem is that the game object called "Player 2" is shooting at himself, the bullet is going in his direction. Even when I rotate the SpawnBullet. In Player 1 it works fine.
This script is attached to the players
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Moviment : MonoBehaviour
{
//player variables
public GameObject player;
public GameObject[] Personagens;
//moving variables
Vector3 targetPosition;
float posY = 1;
public float velocity = 0.2f;
public float movMax = 3;
public bool ismoving = false;
public bool moveEnabled;
public int aux;
//bullet variables
public GameObject projetil;
private GameObject SpawBala;
public float ProjetilVeloc = 500f;
private void Start()
{
//sets the first unit as the active unit at the start of the game
Personagens[0].GetComponent<Jogador>().isPlayer = true;
TurnStart();
}
// Update is called once per frame
void Update()
{
//left mouse button to start movement
if (Input.GetMouseButtonDown(0))
{
//raycast checks and returns an object, if it's a tile, the unit moves
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
ismoving = true;
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.tag == "Tile")
{
//checks if the tile is available based on the max movement of the unit
Tile tileAux = hit.transform.gameObject.GetComponent<Tile>();
Jogador scriptJog = player.GetComponent<Jogador>();
if ((tileAux.TilePostion.x - scriptJog.GridPosition.x) + (tileAux.TilePostion.y - scriptJog.GridPosition.y) >= -movMax && (tileAux.TilePostion.x - scriptJog.GridPosition.x) + (tileAux.TilePostion.y - scriptJog.GridPosition.y) <= movMax)
{
if ((tileAux.TilePostion.x - scriptJog.GridPosition.x) - (tileAux.TilePostion.y - scriptJog.GridPosition.y) >= -movMax && (tileAux.TilePostion.x - scriptJog.GridPosition.x) - (tileAux.TilePostion.y - scriptJog.GridPosition.y) <= movMax)
{
targetPosition = (hit.transform.position);
targetPosition.y = posY;
moveEnabled = true;
}
}
}
}
}
//right click to shoot
if (Input.GetMouseButtonDown(1))
{
//raycast checks and returns an object, if it's a tile, the unit shoots
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//checks if the tile is available based on the line and column of the unit
Tile tileAux = hit.transform.gameObject.GetComponent<Tile>();
Jogador scriptJog = player.GetComponent<Jogador>();
if (tileAux.TilePostion.x == scriptJog.GridPosition.x || tileAux.TilePostion.y == scriptJog.GridPosition.y)
{
if (tileAux.TilePostion.x > scriptJog.GridPosition.x)
tileAux.TilePostion.x = 5;
else
tileAux.TilePostion.x = 0;
if (tileAux.TilePostion.y > scriptJog.GridPosition.y)
tileAux.TilePostion.y = 5;
else
tileAux.TilePostion.y = 0;
Debug.Log(tileAux.TilePostion.x);
Debug.Log(tileAux.TilePostion.y);
//instantiates the bullet
GameObject tiro = Instantiate(projetil, SpawBala.transform.position, Quaternion.identity, player.transform);
Rigidbody BalaRigid = tiro.GetComponent<Rigidbody>();
BalaRigid.AddForce(Vector3.forward * ProjetilVeloc);
}
}
}
//player moves until reaches the position
if (player.transform.position != targetPosition)
{
player.transform.position = Vector3.MoveTowards(player.transform.position, targetPosition, velocity);
if (player.transform.position == targetPosition)
ismoving = false;
}
//if player reaches position, it's deselected
if (moveEnabled && !ismoving)
{
player.GetComponent<Jogador>().isPlayer = false;
moveEnabled = false;
}
}
public void TurnStart()
{
//makes the selected unit the active unit
for (int i = 0; i < Personagens.Length; i++)
{
if (Personagens[i].GetComponent<Jogador>().isPlayer == true)
{
player = Personagens[i];
posY = player.transform.position.y;
targetPosition = player.transform.position;
SpawBala = player.transform.GetChild(0).gameObject;
}
}
}
public void TurnEnd()
{
//desactivates all units
for(int i = 0; i < Personagens.Length; i++)
{
Personagens[i].GetComponent<Jogador>().isPlayer = false;
}
}
}
And I'm using this section (copied from above) to shoot:
//right click to shoot
if (Input.GetMouseButtonDown(1))
{
//raycast checks and returns an object, if it's a tile, the unit shoots
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//checks if the tile is available based on the line and column of the unit
Tile tileAux = hit.transform.gameObject.GetComponent<Tile>();
Jogador scriptJog = player.GetComponent<Jogador>();
if (tileAux.TilePostion.x == scriptJog.GridPosition.x || tileAux.TilePostion.y == scriptJog.GridPosition.y)
{
if (tileAux.TilePostion.x > scriptJog.GridPosition.x)
tileAux.TilePostion.x = 5;
else
tileAux.TilePostion.x = 0;
if (tileAux.TilePostion.y > scriptJog.GridPosition.y)
tileAux.TilePostion.y = 5;
else
tileAux.TilePostion.y = 0;
Debug.Log(tileAux.TilePostion.x);
Debug.Log(tileAux.TilePostion.y);
//instantiates the bullet
GameObject tiro = Instantiate(projetil, SpawBala.transform.position, Quaternion.identity, player.transform);
Rigidbody BalaRigid = tiro.GetComponent<Rigidbody>();
BalaRigid.AddForce(Vector3.forward * ProjetilVeloc);
}
}
}
When you add the force to the bullet you are using Vector3.forward. You need to use transform.forward instead.
Vector3.forward is always a constant (0, 0, 1). Think of the it as the forward direction of your world. It never changes.
transform.forward however will give the forward facing direction of the gameObject (the player). When you rotate your player it's transform.forward will change accordingly.
The reason Player 1 appears to be working correctly is because it is facing the same direction as Vector3.forward.

Categories

Resources