- Home /
Stop checking for values in Update function?
So, I'm trying to make a shooting mechanism for my 2D platformer, and the way I have it going in the right direction is by using the facingRight
boolean (line 25-29). The problem is (and you can probably see it) is that when the player changes directions, the bullet does too. Does anyone know how to stop from checking values (EDIT: or keeping values the same) WHILE letting the player shoot still? Any suggestion is welcome. Thanks! BTW here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
private Vector2 target;
public float speed;
public GameObject player;
public PlayerController pController;
public bool facingRight;
private Transform playerTransform;
void Start () {
player = GameObject.Find("Player");
pController = player.GetComponent<PlayerController>();
playerTransform = player.GetComponent<Transform>();
}
void Update () {
facingRight = pController.facingRight;
Debug.Log(facingRight);
if (facingRight == true) {
target = new Vector2(playerTransform.position.x + 30, playerTransform.position.y);
} else {
target = new Vector2(playerTransform.position.x - 30, playerTransform.position.y);
}
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, target) < 0.2f) {
Destroy(gameObject);
}
}
}
Answer by JDelekto · Jun 23, 2018 at 09:56 AM
Since I imagine that you are creating the projectile when the user fires, you will probably want to save the initial state of the direction the player was facing and the target position in your Start() method. Then, only do the movement of the projectile using these initial values, so your new Start() and Update() methods would look something like this:
void Start()
{
player = GameObject.Find("Player");
pController = player.GetComponent<PlayerController>();
playerTransform = player.GetComponent<Transform>();
target = new Vector2(playerTransform.position.x + (pController.facingRight ? 30 : -30), playerTransform.position.y);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, target) < 0.2f)
{
Destroy(gameObject);
}
}
Answer by belwar · Jun 23, 2018 at 10:00 AM
If the bullet changes direction when the player does, I suppose you spawn the bullets as childs of the player object.
Try to spawn them at the root (or as childs of another object but not the player).
They already are as root. I think it's cause they are constantly updating the target based on the player's direction.