using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
Player player;
public float projectileSpeed;
// Start is called before the first frame update
void Start()
{
player = FindObjectOfType<Player>();
}
// Update is called once per frame
void Update()
{
if (player.turnedRight == true)
{
transform.Translate(Vector3.right * projectileSpeed * Time.deltaTime);
}
else if (player.turnedRight == false)
{
transform.Translate(Vector3.left * projectileSpeed * Time.deltaTime);
}
}
}
So its my projectile code, and i have problem cause when i turn my character by pressing a or d when projectile is spawned the projectile also changing the direction that is going but i dont want that i want when projectile is spawned when character is turned right the projectile go right no matter what but i dont rly have any idea how to make that any tips ?
Move your turnedRight check to Start and set a class variable to left or right, then use that variable in Update function to move your projectile.
1 Like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
public Player player;
public bool travelRight;
public bool travelLeft;
public float projectileSpeed;
// Start is called before the first frame update
void Start()
{
player = FindObjectOfType<Player>();
if (player.turnedRight == true)
{
travelRight = true;
}
else if (player.turnedRight == false)
{
travelLeft = true;
}
}
// Update is called once per frame
void Update()
{
if (travelRight == true)
{
TravelRight();
}
else if (travelLeft == true)
{
TravelLeft();
}
}
void TravelLeft()
{
transform.Translate(Vector3.left * projectileSpeed * Time.deltaTime);
}
void TravelRight()
{
transform.Translate(Vector3.right * projectileSpeed * Time.deltaTime);
}
}
Its working while projectile is spawned its not changing directions but there is a little problem even when my character is turned left my projectiles going right all the time i tried do figured it out my self but im kinda stuck the right bools getting checked but its always calling function TravelRight()
Try to make variables private.
Let’s simplify your code a little and add some log
private Vector3 direction;
void Start()
{
player = FindObjectOfType<Player>();
Debug.LogFormat("Is player turned right? {0}", player.turnedRight);
if (player.turnedRight)
{
direction = Vector3.right;
}
else
{
direction = Vector3.left;
}
}
// Update is called once per frame
void Update()
{
transform.Translate(direction * projectileSpeed * Time.deltaTime);
}
What it prints now?