unity projectile spawns but doesn't pick up velocity? - c#

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!

Related

My Bullet is not getting instantiated where my Player is. It is getting instantiated from center only

I am new to Unity & on Stackoverflow. Need your help as I am stuck in this below mentioned situation.
When I spawn my projectile(Bullet), It should be instantiated at player's current position but It's not getting changed. The bullet is getting generated from Center only(Not from Player's position). Please advise. image is for reference
SpawnobjectController Script
public class SpawnobjectController : MonoBehaviour
{
[SerializeField]
GameObject projectilereference;
[SerializeField]
GameObject enemyreference;
[SerializeField]
GameObject playerreference;
void Start()
{
StartCoroutine(Enemycoroutine());
StartCoroutine(ProjectileCoroutine());
}
void SpawnProjectile()
{
Instantiate(projectilereference, new Vector3(playerreference.transform.position.x,projectilereference.transform.position.y,0.0f), Quaternion.identity);
}
IEnumerator ProjectileCoroutine()
{
while (true)
{
SpawnProjectile();
yield return new WaitForSeconds(2.0f);
}
}
IEnumerator Enemycoroutine()
{
while (true) {
SpawnEnemy();
yield return new WaitForSeconds(1.0f);
}
}
void SpawnEnemy()
{
Instantiate(enemyreference, enemyreference.transform.position, Quaternion.identity);
}
}
PlayerController Scripts
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
float _horizontalAxisPlayer;
float _playerSpeed = 5f;
float _maxXBoundry = 2.31f;
void Start()
{
}
void Update()
{
ControlPlayerBoundries();
PlayerMovement();
}
void PlayerMovement()
{
_horizontalAxisPlayer = Input.GetAxis("Horizontal")*_playerSpeed*Time.deltaTime;
transform.Translate(new Vector3(_horizontalAxisPlayer, 0.0f, 0.0f));
}
void ControlPlayerBoundries()
{
if (transform.position.x>_maxXBoundry)
{
transform.position = new Vector3(_maxXBoundry,transform.position.y,0.0f);
}
else if (transform.position.x<-_maxXBoundry)
{
transform.position = new Vector3(-_maxXBoundry, transform.position.y, 0.0f);
}
}
}
EnemyController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
[SerializeField]
private float enemeySpeed = 2f;
void Start()
{
}
void Update()
{
transform.Translate(Vector3.down * enemeySpeed * Time.deltaTime);
}
}
ProjectileController Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileController : MonoBehaviour
{
[SerializeField]
private GameObject Playerref;
[SerializeField]
private float projectile_speed = 2f;
void Start()
{
}
void Update()
{
// print(Playerref.transform.position);
}
private void LateUpdate()
{
transform.Translate(new Vector3(transform.position.x, 0.5f) * projectile_speed * Time.deltaTime);
}
}
Your problem is likely in the script that translates your bullet.
As the code you shared does exactly what you want. Assuming we are in a front view.
I have verified this by using your script and a copy of the enemy script in place of a bullet that moves them in Vector3.Up direction.
Edit:
You are creating a new vector with the transforms x and 0,5f that gets added every frame.
You either set transform.position or use Translate but with a direction only.
Moves the transform in the direction and distance of translation.
transform.Translate(Vector3 translation)
The following line would work instead.
private void LateUpdate()
{
transform.Translate(Vector3.up * projectile_speed* Time.deltaTime);
}

Moving an object towards a position not working properly

I have written a code to get a random transform from my list pathPoints and move my object based on that transform, but what it is doing is getting multiple transforms and trying to move everywhere at once. I want the object to move at one position then get a new position and move there then repeat.
Here is the code:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathFinder : MonoBehaviour
[SerializeField] List<Transform> pathPoints;
[SerializeField] Transform pathPrefab;
[SerializeField] float moveSpeed = 10f;
[SerializeField] bool isMoving = false;
[SerializeField] bool isH_Attacking = false;
Animator anim;
Transform defaultWayPoint;
Transform currentTargetPoint;
void Awake()
{
anim = GetComponent<Animator>();
defaultWayPoint = pathPrefab.GetChild(0);
}
void Start()
{
currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
transform.position = defaultWayPoint.position;
}
void MoveToNextWayPoint()
{
if(transform.position != currentTargetPoint.position)
{
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
anim.SetBool("isMoving", true);
isMoving = true;
}
GetNextWayPoint();
}
Transform GetNextWayPoint()
{
currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
Debug.Log(currentTargetPoint.position);
return currentTargetPoint;
}
void Update()
{
MoveToNextWayPoint();
}
*The script is attached to the gameObject which I want to move.
*This is a 2d project.
void MoveToNextWayPoint()
{
if(transform.position != currentTargetPoint.position)
{
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
anim.SetBool("isMoving", true);
isMoving = true;
}
else
{
GetNextWayPoint();
}
}

Why does the client sees himself falling through the ground?

Recently I tried making a multiplayer game and I have some problems. After I click "Play" in the menu and I get placed in the multiplayer scene, I see myself falling through the ground, and when I check the "Scene" tab in unity my character is standing where it should be and responds to my movements (as a player, all I can see is the infinite nothing around me but I can still look around, move, etc). When another player connects, he is bugged into the ground (and I can see the shadow from the other player that is hosting and plays directly from unity) and I can't move at all.
Code :
So in the main menu scene, I have this :
NetworkController script :
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NetworkController : MonoBehaviourPunCallbacks
{
void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster () {
Debug.Log("coonnected to " + PhotonNetwork.CloudRegion + " server !");
}
void Update()
{
}
}
QuickStartLobbyController script:
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartLobbyController : MonoBehaviourPunCallbacks
{
[SerializeField] GameObject quickStartButton;
[SerializeField] float roomSize;
public override void OnConnectedToMaster () {
PhotonNetwork.AutomaticallySyncScene = true;
quickStartButton.SetActive(true);
}
public void QuickStart () {
quickStartButton.SetActive(false);
PhotonNetwork.JoinRandomRoom();
Debug.Log("Quick Start!");
}
public override void OnJoinRandomFailed (short returnCode, string message) {
Debug.Log("Failed to join a room");
CreateRoom();
}
public void CreateRoom () {
Debug.Log("creating room");
int randomRoomNumber = Random.Range(0, 10000);
RoomOptions roomOps = new RoomOptions() { IsVisible = true, IsOpen = true, MaxPlayers = (byte)
roomSize };
PhotonNetwork.CreateRoom("Room" + randomRoomNumber, roomOps);
Debug.Log(randomRoomNumber);
}
public override void OnCreateRoomFailed (short returnCode, string message) {
Debug.Log("failed to create a room");
CreateRoom();
}
}
QuickStartRoomController script :
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomController : MonoBehaviourPunCallbacks
{
[SerializeField] int multiplayerSceneIndex;
public override void OnEnable () {
PhotonNetwork.AddCallbackTarget(this);
}
public override void OnDisable () {
PhotonNetwork.RemoveCallbackTarget(this);
}
public override void OnJoinedRoom () {
Debug.Log("joined room");
StartGame();
}
private void StartGame () {
if ( PhotonNetwork.IsMasterClient ) {
Debug.Log("Starting game");
PhotonNetwork.LoadLevel(multiplayerSceneIndex);
}
}
}
And now, the multiplayer scene where players should see each other:
The player has those :
The script inside GameSetup:
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class GameSetupController : MonoBehaviour
{
void Start()
{
CreatePlayer();
}
private void CreatePlayer () {
Debug.Log("Creating Player");
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "player"), Vector3.zero,
Quaternion.identity);
}
}
EDIT: so here you can see exactly how it looks like. When I play from the editor's window I can move around even if I can't see it, but with the client, I cannot do basically anything in-game. I think it might be a problem with the GameSetup code or with the part that syncs all the players with the server
EDIT2: posted the playerController script :
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour, IPunObservable {
[SerializeField] Transform camera;
[SerializeField] float sens = 3.5f;
[SerializeField] float walkSpeed = 6.0f;
[SerializeField] [Range(0.0f, 0.5f)] float smooth = 0.3f;
[SerializeField] [Range(0.0f, 0.5f)] float smoothMouse = 0.3f;
[SerializeField] float gravity = -13.0f;
[SerializeField] float slopeForce = 6;
[SerializeField] float slopeForceRayLenght = 1.5f;
[SerializeField] float runSpeed = 10;
[SerializeField] float runBuildUp = 4;
[SerializeField] float jumpForce = 10;
[SerializeField] KeyCode jumpk;
[SerializeField] KeyCode runk;
[SerializeField] bool cursorLock = true;
public Rigidbody rb;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask grndMask;
public bool isGrounded;
float cameraPitch = 0.0f;
float velocityY = 0.0f;
float speed;
Vector2 currentDir = Vector2.zero;
Vector2 currentDirVelocity = Vector2.zero;
Vector2 currentMouseDelta = Vector2.zero;
Vector2 currentMouseDeltaVelocity = Vector2.zero;
CharacterController controller;
PhotonView photonView;
private void Awake () {
photonView = GetComponent<PhotonView>();
photonView.ObservedComponents.Add(this);
if ( !photonView.IsMine ) {
enabled = false;
}
}
void Start () {
speed = walkSpeed;
controller = GetComponent<CharacterController>();
if ( cursorLock ) {
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
// Update is called once per frame
void Update () {
UpdateMouseLook();
UpdateMovement();
Jump();
}
void UpdateMouseLook () {
Vector2 mouseDelta = new Vector2(Input.GetAxis("Mouse
X"),Input.GetAxis("Mouse Y"));
currentMouseDelta = Vector2.SmoothDamp(currentMouseDelta, mouseDelta,ref
currentMouseDeltaVelocity, smoothMouse);
cameraPitch -= currentMouseDelta.y * sens;
cameraPitch = Mathf.Clamp(cameraPitch, -90.0f, 90.0f);
camera.localEulerAngles = Vector3.right * cameraPitch;
transform.Rotate(Vector3.up * currentMouseDelta.x * sens);
}
void SetSpeed () {
if ( Input.GetKey(runk) ) {
speed = Mathf.Lerp(speed, runSpeed, Time.deltaTime * runBuildUp);
} else {
speed = Mathf.Lerp(speed, walkSpeed, Time.deltaTime * runBuildUp);
}
}
void Jump () {
isGrounded = Physics.CheckSphere(groundCheck.position,
groundDistance,grndMask);
if ( isGrounded && Input.GetKeyDown(jumpk) ) {
Debug.Log("jumping");
velocityY = Mathf.Sqrt(jumpForce * -2f * gravity);
controller.Move(Vector3.up * velocityY * Time.deltaTime);
}
}
public bool OnSlope () {
RaycastHit hit;
if ( Physics.Raycast(transform.position, Vector3.down, out hit,
controller.height / 2 * slopeForceRayLenght) ) {
if ( hit.normal != Vector3.up ) {
return true;
}
}
return false;
}
void UpdateMovement () {
Vector2 inputDir = new Vector2(Input.GetAxisRaw("Horizontal"),
Input.GetAxisRaw("Vertical"));
inputDir.Normalize();
currentDir = Vector2.SmoothDamp(currentDir, inputDir, ref
currentDirVelocity, smooth);
if ( controller.isGrounded ) {
velocityY = 0.0f;
}
velocityY += gravity * Time.deltaTime;
Vector3 velocity = (transform.forward * currentDir.y + transform.right *
currentDir.x) * speed + Vector3.up * velocityY;
controller.Move(velocity * Time.deltaTime);
if ( (inputDir.x != 0 || inputDir.y != 0) && OnSlope() ) {
controller.Move(Vector3.down * controller.height / 2 * slopeForce *
Time.deltaTime);
}
SetSpeed();
}
void IPunObservable.OnPhotonSerializeView (PhotonStream stream,
PhotonMessageInfo info) {
if ( stream.IsWriting ) {
// We own this player: send the others our data
stream.SendNext(transform.position); //position of the character
stream.SendNext(transform.rotation); //rotation of the character
} else {
// Network player, receive data
Vector3 syncPosition = (Vector3) stream.ReceiveNext();
Quaternion syncRotation = (Quaternion) stream.ReceiveNext();
}
}
}
EDIT3: I found out something! When I enter the game from the master, I still need to drag myself up a bit in the editor and I will stop falling and I can play the game, but when the 2nd player connects, My camera is set to his (in all this time I can move my character and see this through the 2nd player's camera), and when he leaves all go back to normal on the master player. However, with the 2nd player, I can't move and I get an error that says:5. Btw the 2nd player is the session from the standalone (the built game) and the first player is a session from the unity editor

How to make a player die while falling?

I am developing a basic game on Unity to improve myself. It's a basic endless runner platform game.
If you right click when the player is on the ground, it jumps; if it's not on the ground, it falls faster.
But I couldn't figure out how to make a player die while falling when it couldn't catch the platform. Could you please check my code? I am trying to find an "if" command to make it happen.
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerControls : MonoBehaviour
{
public Rigidbody2D rb;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
float CurrentFallTime;
public float MaxFallTime = 7;
bool PlayerIsFalling;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
rb.velocity = new Vector2(5, rb.velocity.y);
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
CurrentFallTime += Time.deltaTime;
if (Input.GetMouseButtonDown(0) && onGround)
{
rb.velocity = new Vector2(rb.velocity.x, 12);
}
if (Input.GetMouseButtonDown(0) && !onGround)
{
rb.velocity = new Vector2(rb.velocity.x, -10);
}
// I want it to die and go to game over screen when it exceeds the CurrentFallTime
if ()
{
if (CurrentFallTime >= MaxFallTime)
{
SceneManager.LoadScene("GameOver");
}
}
}
}
EDIT: It solved! I simpy added "if(onGround)" and reset the CurrentFallTime. Here is the new code:
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerControls : MonoBehaviour
{
public Rigidbody2D rb;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
float CurrentFallTime;
public float MaxFallTime = 7;
bool PlayerIsFalling;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
rb.velocity = new Vector2(5, rb.velocity.y);
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
CurrentFallTime += Time.deltaTime;
if (onGround)
{
CurrentFallTime = 0f;
}
if (Input.GetMouseButtonDown(0) && onGround)
{
rb.velocity = new Vector2(rb.velocity.x, 12);
}
if (Input.GetMouseButtonDown(0) && !onGround)
{
rb.velocity = new Vector2(rb.velocity.x, -10);
}
if (CurrentFallTime >= MaxFallTime)
{
SceneManager.LoadScene("GameOver");
}
}
}
This is something that I just thought of now, so I'm not sure how well it will work, but you can create a 1-sided plane collider and position it to follow the x- and y-coordinate of the player, but stay slightly lower than the height of the ground, e.g. 1unit. Then check when the player collides with the plane, if it does then you know that the player has fallen.
So, create an empty GameObject and add the collider, no need for any mesh properties and set the collider trigger to true. Then in player controls add something like in update.
colliderGo.transform.location = new Vector3(transform.x, groundHeight - 1, transform.z)
Also in the player controller function
function onTrigger(Collider col) {
if (col.tag == "fallDetector") {
Debug.Log("What a cruel world")
playHasFallen = true;
}
}
Something like this should work.

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

Categories