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 :)
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'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;
}
I'm making a game and I want jumping to feel like jumping in Super Mario Bros. I'm able to get the result I want with a Keyboard or a Controller because they have KeyDown, Key (While pressed), and KeyUp. But touchButtons only have a single boolean. (Pressed or Not Pressed) Is there a way I can work around this?
I tried using Input.GetTouch and using the begin and end phase, this gave the correct result but I'm not sure how to implement it into a GUI button.
The code I'm using has a GUI button with a script that when the button is pressed, joybutton.Pressed = true
void PlayerJump()
{
bool canJump = charController.isGrounded;
//Button Pressed start jumpDuration
if (joybutton.Pressed && canJump)
{
isJumping = true;
jumpDuration = jumpTime;
}
if (isJumping == true)
{
if (jumpDuration > 0)
{
vertical_Velocity = jump_Force;
jumpDuration -= Time.deltaTime;
}
//timer runs out
else
{
isJumping = false;
}
}
//cancel jump if mid-air
if (!joybutton.Pressed)
{
isJumping = false;
}
}
I have no way of stopping the player from jumping as soon as they land with the GUI touchButton. I get desired results with keyboard and gamepad buttons.
Add a variable to remember the state of the button last frame. That way, you can enter the jump start block only if it's the first frame of the button being hit:
private bool wasJumpPressedLastFrame = false;
void PlayerJump()
{
bool canJump = charController.isGrounded;
//Button Pressed start jumpDuration
if (joybutton.Pressed && canJump && !wasJumpPressedLastFrame )
{
isJumping = true;
jumpDuration = jumpTime;
}
if (isJumping == true)
{
if (jumpDuration > 0)
{
vertical_Velocity = jump_Force;
jumpDuration -= Time.deltaTime;
}
//timer runs out
else
{
isJumping = false;
}
}
//cancel jump if mid-air
if (!joybutton.Pressed)
{
isJumping = false;
}
wasJumpPressedLastFrame = joyButton.Pressed;
}
I almost have a working radio, where the player can walk up to it, press a button and cycle through songs. Everything works except for that with each button press the new song will play but the original will continue to play underneath it. For each new song that is played a new object is created but they are all called 'One Shot Audio,' so I don't know how to destroy them. If I can fix this bug then this should be a useful radio script for anyone who wants to use it.
Update, here is my modified radio code, now working, with the help of the answer below:
void OnTriggerEnter2D(Collider2D target) {
if (target.gameObject.tag == "radio") {
radioEnter = true;
}
}
void OnTriggerExit2D(Collider2D target) {
if (target.gameObject.tag == "radio") {
radioEnter = false;
}
}
public void radioUse(){
if ((Input.GetKeyDown (KeyCode.M)) && song3on == true && radioEnter == true) {
TurnOn ();
song1on = true;
song2on = false;
song3on = false;
}
else if ((Input.GetKeyDown (KeyCode.M)) && song1on == true && radioEnter == true) {
TurnOff ();
song1on = false;
song2on = true;
song3on = false;
TurnOn();
}
else if ((Input.GetKeyDown (KeyCode.M)) && song2on == true && radioEnter == true) {
TurnOff ();
song1on = false;
song2on = false;
song3on = true;
TurnOn ();
}
}
public void Update() {
raidoUse();
}
Since PlayClipAtPoint does not return an AudioSource to manage you should not use it for these kind of sounds. I recommend setting up your radio with one AudioSource and multiple AudioClips in a array. Just drag the clips you want to the inspector and use the public methods to control the radio. This way you can reuse it with different songs.
The following code is not tested.
Public class Radio : MonoBehaviour
{
AudioSource output;
public AudioClip[] songs;
int songIndex = 0;
void Start(){
output = gameObject.AddComponent<AudioSource>();
}
public void ToggleSong(){
songIndex++;
output.clip = songs[songIndex % songs.Length];
output.Play();
}
public void TurnOn(){
ToggleSong();
}
public void TurnOff(){
output.Stop();
}
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;
}
}