I'm making a endless runner game. And would like to increase the health/life when a certain score has reached. In a ScoreManager script attached to a ScoreManager I have:
public class ScoreManager : MonoBehaviour
{
public int score;
public Text scoreDisplay;
bool one = true;
Player scriptInstance = null;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
Debug.Log(score);
}
}
// Start is called before the first frame update
void Start()
{
GameObject tempObj = GameObject.Find("ghost01");
scriptInstance = tempObj.GetComponent<Player>();
}
// Update is called once per frame
private void Update()
{
scoreDisplay.text = score.ToString();
if (scriptInstance.health <= 0)
{
Destroy(this);
}
if (score == 75 || score == 76 && one == true)
{
scriptInstance.health++;
one = false;
}
}
I used the following lines to increase the health at a milestone, but have to copy the code endlessly to create multiple milestones.
if (score == 75 || score == 76 && one == true)
{
scriptInstance.health++;
one = false;
}
My question is how to increase health every 75 points, without duplicating the code?
The issue with a modulo like if(score % 75 == 0) would be that it returns true all the time while score == 75 .. so it would require an additional bool flag anyway.
I would rather simply add a second counter for this!
And not check things repeatedly in Update at all but rather the moment you set it:
int healthCounter;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
Debug.Log(score);
// enough to update this when actually changed
scoreDisplay.text = score.ToString();
healthCounter++;
if(healthCounter >= 75)
{
scriptInstance.health++;
// reset this counter
healthCounter = 0;
}
}
}
the one drawback maybe is that know you have to reset the healthCounter = 0 wherever you reset the score = 0 ... but you would have to do the same with any flag solution as well ;)
I would go with th % operator
private bool scoreChanged = false;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
scoreChanged = true;
Debug.Log(score);
}
}
if (score % 75 == 0 && scoreChanged)
{
scriptInstance.health++;
scoreChanged = false;
}
Related
I'm making a platformer for my A Level programming project where the player automatically jumps on a platform upon touching it. However, I'm having trouble with the collision detection because it only bounces on one platform and falls right through the rest. they all have the same tags so i know that's not the issue.
the way that it's coded is that it will detect collision with any rectangle with the tag 'platform' however it only detects collision with 1 rectangle
Code sample below:
public partial class MainWindow : Window
{
private DispatcherTimer GameTimer = new DispatcherTimer();
private bool LeftKeyPressed, RightKeyPressed, gravity;
double score;
//this value will increase to be 5x the highest Y value so the score increases the higher Meke gets
private float SpeedX, SpeedY, FrictionX = 0.88f, Speed = 1, FrictionY = 0.80f;
//SpeedX controls horizontal movement, SpeedY controls vertical movement
private void Collide(string Dir)
{
foreach (var x in GameScreen.Children.OfType<Rectangle>())
{
if (x.Tag != null)
{
var platformID = (string)x.Tag;
if (platformID == "platform")
{
x.Stroke = Brushes.Black;
Rect MeekHB = new Rect(Canvas.GetLeft(Meek), Canvas.GetTop(Meek), Meek.Width, Meek.Height);
Rect PlatformHB = new Rect(Canvas.GetLeft(x), Canvas.GetTop(x), x.Width, x.Height);
int Jumpcount = 1;
if (MeekHB.IntersectsWith(PlatformHB))
{
if (Dir == "y")
{
while (Jumpcount != 700)
{
gravity = false;
Jumpcount = Jumpcount + 1;
}
}
}
else
{
gravity = true;
}
}
}
}
}
private void KeyboardUp(object sender, KeyEventArgs e)
{
//this is what detects when the 'A' key is being pressed
if (e.Key == Key.A)
{
LeftKeyPressed = false;
}
if (e.Key == Key.D)
{
RightKeyPressed = false;
}
}
private void KeyboardDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.A)
{
LeftKeyPressed = true;
}
if (e.Key == Key.D)
{
RightKeyPressed = true;
}
}
public MainWindow()
{
InitializeComponent();
GameScreen.Focus();
GameTimer.Interval = TimeSpan.FromMilliseconds(16);
GameTimer.Tick += GameTick;
GameTimer.Start();
}
private void GameTick(Object Sender, EventArgs e)
{
txtScore.Content = "Score: " + score;
if (LeftKeyPressed)
{
SpeedX -= Speed;
}
if (RightKeyPressed)
{
SpeedX += Speed;
}
if (gravity == true)
{
SpeedY += Speed;
}
else if (gravity == false)
{
SpeedY -= Speed+50;
}
SpeedX = SpeedX * FrictionX;
SpeedY = SpeedY * FrictionY;
Canvas.SetLeft(Meek, Canvas.GetLeft(Meek) + SpeedX);
Collide("x");
Canvas.SetTop(Meek, Canvas.GetTop(Meek) + SpeedY);
Collide("y");
double maxY = 0;
if (Canvas.GetBottom(Meek) > maxY)
{
maxY = Canvas.GetBottom(Meek);
}
score = maxY;
}
}
}
I think there is an error in your gravity = true logic. You make check for intersections in loop for all platforms, so even if first platform in loop sets gravity to false, next platform in loop will set gravity to true again and logic won't work. As far as I understand, your logic works only to detect last platform in GameScreen.Children.OfType(). Maybe try to break; you loop after you found an intersection.
And for future - add some logs to your app to be able to debug such issues. Most likely your game library provide some ways to print debug messages - add them to your code so you can see, what's going on.
And also your while (Jumpcount != 700) loop looks useless
I am trying to implement two touch functions. One tap and long tap. I have implemented one tap which is pretty straightforward but for a long tap function, a timer must be set?
I would like the long press to be active only after 1 second of holding the tap and then the timer should get reset on release. How do I do this?
public float longTapTime;
void Update()
{
if ((Input.touchCount > 0) && (Input.GetTouch (0).phase == TouchPhase.Began)) {
//One tap
}
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
longTapTime = 0;
}
}
using UnityEngine;
public class example : MonoBehaviour
{
[SerializeField]
private float long_tap_consider_duration = 1.0f;
private float time_helper;
private float duration;
private bool is_touched;
private void Start()
{
time_helper = 0;
duration = 0;
is_touched = false;
}
private void Update()
{
if (Input.touchCount > 0)
ProcessInput();
}
private void ProcessInput()
{
if (is_touched && ((Input.GetTouch(0).phase == TouchPhase.Ended) || (Input.GetTouch(0).phase == TouchPhase.Canceled)))
{
if (duration > long_tap_consider_duration)
OnLongTap();
else OnTap();
}
if (!is_touched && (Input.GetTouch(0).phase == TouchPhase.Began))
{
time_helper = Time.time;
is_touched = true;
}
duration = Time.time - time_helper;
}
//Callback function, when just a short tap occurs
private void OnTap()
{
Debug.Log("Short Tap");
}
//Callback function, when long tap occurs
private void OnLongTap()
{
Debug.Log("Long Tap");
}
}
actually, if you are using the new input system, this is a built in feature and does not need any code.
find your Input Actions ".inputActions"
find the button on the list of inputs registered
with that item selected, find the plus "+" next to the word interactions on the right hand side
add a "hold" interaction from the list and set desired hold time.
for more information on the input action asset system: https://www.youtube.com/watch?v=mvuXOyKz7k4
I've made a unity3d game and I want to add UI . I've started with a pause button but it doesn't seem to work.
Here is the button info:
I've created an uiManager script to manage the button , as shown in the image above and here is the code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class myUIManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
}
if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}
}
Here is the canvas screenshot :
Any ideas? I've been searching for hours ..
I think your problem is in your Pause method:
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
}
if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}
If you enter the first if statement you set Time.timeScale = 0 - and then you immediately go into the second if and set it back to 1.
Try this - it returnss from the Pause method once it sets the Time.timeScale to 0.
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
return;
}
if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}
If the only two things you want to do in your Pause method are to set the Time.timeScale to 0 or 1, you could even simplify it to this:
public void Pause() //Function to take care of Pause Button..
{
print("Entered Pause Func");
if (Time.timeScale == 1 && paused == false) //1 means the time is normal so the game is running..
{
print("Enterer first if");
Time.timeScale = 0; //Pause Game..
}
else
{
Time.timeScale = 1; //Resume Game..
}
}
if the condition of your first if statement is true then you set your timeScale to 0 then the condition of the second if becomes true then you set it back to 1 You should just change your second if to an else if so that if the first condition is true then your program wont check the second one.
public void Pause()
{
if (Time.timeScale == 1)
{
Time.timeScale = 0;
}
else if (Time.timeScale == 0)
{
Time.timeScale = 1; //Resume Game..
}
}
I'm working on making a drone-type enemy that has a sensor that sticks out in front of it. I've been stuck on it for a while now, the problem is that I want the drone to not attack immediately after it detects the player, and for it to stay in suspicious mode a little while after the player leaves the drone's field of view. I'm relatively new to coding so my code is a bit of a mess.
void Update () {
if (dTect == true && dTime > -1.6) {
dTime -= Time.deltaTime;
if (dTime < -1.5f) {
aTak = true;
animator.SetTrigger ("Host");
animator.ResetTrigger ("Susp");
} else {
dTect = false;
//animator.ResetTrigger ("Susp");
}
}
if (dTect == false && dTime > 2.1) {
dTime += Time.deltaTime;
}
if (dTime > 2) {
aTak = false;
animator.SetTrigger ("Susp");
animator.ResetTrigger ("Host");
}} void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.CompareTag("Player")){
dTime = 0;
dTect = true;
animator.SetTrigger("Susp");
}
}
void OnTriggerExit2D(Collider2D other){
if (other.gameObject.CompareTag ("Player")) {
dTime = 0;
dTect = false;
}
}
Any help or advice at all would be greatly appreciated.
void Update()
{
if (dTect == true)
{
dTime += Time.deltaTime;
if (dTime >= 1.5f)
{
aTak = true;
animator.SetTrigger("Host");
animator.ResetTrigger("Susp");
dTect = false;
}
}
if (aTak == true)
{
Attack();
}
}
public void Attack()
{
//fill in whatever you want it to do when attacking
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
dTime = 0;
dTect = true;
sPect = false;
animator.SetTrigger("Susp");
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
dTime = 0;
sPect = true;
dTect = false;
aTak = false;
}
}
I believe the problem was with the timers not adding up correctly and not setting the bools to the right state. Also I would highly recommend looking into using an enum for states instead of booleans, they're a lot easier to use cause you don't have to turn off every other state to change it. Good luck with your game and let me know if this wasn't the solution or if you have any other questions :)
I want to show ads in my 2D game every 5 times the scene is loaded. I tried this:
void Update ()
{
if(GameObject.Find ("Main Camera").transform.position.x == -23) {
showNumber += 1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 1;
}
}
}
How do I make the number only change only once so it would only change once when the main camera's position is -23. Right not it changes every frame.
Edit
void OnTriggerEnter(Collider other) {
DontDestroyOnLoad (gameObject);
if(other.name == "Main Camera") {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 0;
}
}
}
Solution: Put the showNumber +=1 oder showNumber++ into
void Start()
{
showNumber +=1;
}
I think it would be easier if you write this value to a textfile and then read it from this textfile, all in the start event and not the update.
Start is called once and the update is called every frame.
Quick and dirty Edit: Place a trigger zone on your desired postion.
Then call an OnTriggerEnter method.
void OnTriggerEnter(Collider other) {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
Edit: Your problem is that showNumber +=1; is called like 30-60 times, depending on your computer.
You could add a bool variable to check if it's a new entry on that point.
bool alreadyEntered = false;
void Update ()
{
if(GameObject.Find ("Main Camera").transform.position.x == -23 && alreadyEntered == false) {
showNumber += 1;
alreadyEntered = true;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
}
}
if(showNumber > 5) {
showNumber = 1;
}
}
}
Save the Show Number in player prefs.
private int showNumber{
get{
return PlayerPrefs.GetInt("showNumber");
}
set{
PlayerPrefs.SetInt("showNumber",value);
}
}
void OnTriggerEnter(Collider other) {
showNumber +=1;
if(showNumber == 5) {
if(Advertisement.isReady()){
Advertisement.Show();
showNumber = 0;
}
}