Wanting to make a 2D bouncy floating island In Unity c# - c#

I'm new to coding and I am currently wanting to create a floating island that bounces up and down on collision with the player. Note, currently in order for the island to go down on collision, I have a rigidbody on both the player and the island, with the island's gravity scale set to 0 and mass to about 5. This is what I have so far: using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class island : MonoBehaviour
{
public Rigidbody2D rb;
public bool GroundTouch = false;
private void OnCollisionEnter2D(Collision2D collision)
{
GroundTouch = true;
}
private void OnCollisionExit2D(Collision2D collision)
{
GroundTouch = false;
}
private void FixedUpdate()
{
if (GroundTouch == false) {
StartCoroutine(canGoUp());
}
}
IEnumerator canGoUp()
{
functionCalled = false;
yield return new WaitForSeconds(1);
functionCalled = true;
}
bool functionCalled = false;
void Update()
{
if (!functionCalled)
{
Bounce();
}
}
void Bounce()
{
rb.AddForce(transform.up * 20);
}
}

Related

I want to enable my collider again after disabling it

When my character hits the gameobject collider, an enemy will be spawned and the collider is disabled, cuz I do not want to spawn multiple enemies. When my character dies and I have to start from the beginning, the collider should be enabled again to spawn the enemy again.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerSpawner : MonoBehaviour
{
public EnemySpawn enemyspawn;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
enemyspawn.SpawnEnemy();
gameObject.GetComponent<BoxCollider2D>().enabled = false;
}
}
}
//in other class
private void SetHealth(float health)
{
var actualNextHealth = Mathf.Min(m_maxHealth, health);
m_currentHealth = actualNextHealth;
if (m_healthBar != null && m_maxHealth > 0f)
m_healthBar.SetHealth(actualNextHealth / m_maxHealth);
if (m_currentHealth <= 0f)
{
UpdateHighscore();
Die();
}
}
private void Die()
{
m_character.NotifyDied();
if (m_canRespawn)
{
SetVulnerable();
RemovePoison();
m_hazards.Clear();
gameObject.transform.position = m_spawnPosition;
SetHealth(m_maxHealth);
}
else {
Destroy(gameObject);
}
}
You can create a static variable in the trigger script that you assign the Collider value to it.
When an enemy is spawned it deactivates, as in your code.
public class TriggerSpawner : MonoBehaviour
{
public static Collider2D spawnCollider;
public EnemySpawn enemyspawn;
void Start() => spawnCollider.GetComponent<Collider2D>();
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
enemyspawn.SpawnEnemy();
spawnCollider.enabled = false;
}
}
}
When you die, it will reactivate.
private void Die()
{
m_character.NotifyDied();
if (m_canRespawn)
{
TriggerSpawner.spawnCollider.enabled = true;
SetVulnerable();
RemovePoison();
m_hazards.Clear();
gameObject.transform.position = m_spawnPosition;
SetHealth(m_maxHealth);
}
else {
Destroy(gameObject);
}
}
With minimal changes on your code, I'd suggest this:
private void Die()
{
m_character.NotifyDied();
if (m_canRespawn)
{
SetVulnerable();
RemovePoison();
m_hazards.Clear();
gameObject.transform.position = m_spawnPosition;
SetHealth(m_maxHealth);
gameObject.GetComponent<BoxCollider2D>().enabled = true; // add this line
}
else {
Destroy(gameObject);
}
}

The Spawned enemy only moves, but not shoots in unity

I am new to unity. Recently, I have started making a survival fps game, there, I have 1 enemy, when I kill him, it will spawn more enemies. However, the spawned only move, but not shoot. Although, I have attached a script to it. here are all my code.
prefab_shooting-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class prefab_shooting : MonoBehaviour
{
public float damage = 1f;
public float range = 100f;
public GameObject player;
public GameObject enemy;
private void Start()
{
player = GameObject.FindWithTag("Player");
enemy = GameObject.FindWithTag("PBR");
}
private void Update()
{
if (Vector3.Distance(transform.position, player.transform.position) < 25.0f)
{
Debug.Log(damage);
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(enemy.transform.position, enemy.transform.forward, out hit, range))
{
if (hit.transform.tag == "Player")
{
swat_death swat = hit.transform.GetComponent<swat_death>();
// Debug.Log(damage);
}
}
}
}
PBR_shooting (the enemy shooting)-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PBR_shooting : MonoBehaviour
{
public float damage = 1f;
public float range = 100f;
public GameObject player;
public GameObject enemy;
private void Start()
{
player = GameObject.FindWithTag("Player");
enemy = GameObject.FindWithTag("PBR");
}
private void Update()
{
if (Vector3.Distance(transform.position, player.transform.position) < 25.0f)
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if(Physics.Raycast(enemy.transform.position, enemy.transform.forward, out hit, range))
{
if(hit.transform.tag == "Player")
{
swat_death swat = hit.transform.GetComponent<swat_death>();
// Debug.Log(swat.health);
swat.TakeDamage(damage);
}
}
}
Swat_death (player_death) -
using UnityEngine;
using UnityEngine.SceneManagement;
public class swat_death : MonoBehaviour
{
static float health = 250f;
public GameObject player;
public void TakeDamage(float amount)
{
health -= amount;
Debug.Log(health);
if (health <= 0f)
{
Debug.Log("STOP");
SceneManager.LoadScene("death_scene");
}
}
void Die()
{
}
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.tag == "enemy_bullet")
{
//SceneManager.LoadScene("death_scene");
}
}
}
And the PBR_Death (from where the spawning starts) -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PBR_death : MonoBehaviour
{
public GameObject player;
Animator anim;
public int XPos;
public int ZPos;
public GameObject TheEnemy;
public int enemyCount = 0;
public int points = 1;
public GameObject enemyGameObject;
void Start()
{
anim = GetComponent<Animator>();
enemyGameObject = GameObject.FindWithTag("PBR");
}
// Update is called once per frame
void OnCollisionEnter(Collision collision)
{
if (collision.transform.tag == "bullet")
{
anim.SetTrigger("isDying");
enemy_movement enemy = GetComponent<enemy_movement>();
enemy.enabled = false;
PBR_shooting shoot = GetComponent<PBR_shooting>();
shoot.enabled = false;
scoreManager.score += points;
GameObject go = Instantiate(enemyGameObject, new Vector3(Random.Range(34, 0), Random.Range(34, 0), 0), Quaternion.identity) as GameObject;
go.AddComponent<prefab_movement>();
go.AddComponent<prefab_death>();
go.AddComponent<prefab_shooting>();
// StartCoroutine(EnemySpawner());
Destroy(collision.gameObject);
}
}
Pls help me, I am stuck in this for almost 3 days..
You didn't call the function
In your first script (prefab_shooting-) You didn't call the Shoot() function.

I am attempting to make a 2D platformer on Unity but my character keeps flying to side without any input from the controller

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Playerovement : MonoBehaviour
{
PlayerInputActions controls;
public CharacterController2D controller;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
void Awake () {
controls = new PlayerInputActions();
controls.Control.Jump.performed += ctx => Jump();
controls.Control.Horizontal.performed += horizontalMove => Move();
}
void Jump() {
jump = true;
}
void Move() {
controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
}
void OnEnable() {
controls.Control.Enable();
}
void OnDisable() {
controls.Control.Disable();
}
void FixedUpdate()
{
jump = false;
}
}
That is my code. The character controller is linked HERE (https://github.com/Brackeys/2D-Character-Controller/blob/master/CharacterController2D.cs). Please help as my character keeps flying away.

Character does not "see" the player (3D Game)

I am following this unity 3D course. I followed every single step of the part called "Enemies Part 1: Static Observers", and after re-checking the code and doing researches for a day, I still did not find the problem. The scope of this part of the tutorial is to make that when the "Gargoyle" sees the player, when passing in front of him, should restart the game.
These are the two scripts that should make this work, but don't.
Observer (Gargoyle):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Observer : MonoBehaviour
{
public Transform player;
public GameEnding gameEnding;
bool m_IsPlayerInRange;
void OnTriggerEvent(Collider other)
{
if (other.transform == player)
{
m_IsPlayerInRange = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.transform == player)
{
m_IsPlayerInRange = false;
}
}
void Update()
{
if (m_IsPlayerInRange)
{
Vector3 direction = player.position - transform.position + Vector3.up;
Ray ray = new Ray(transform.position, direction);
RaycastHit raycastHit;
if (Physics.Raycast(ray, out raycastHit))
{
if (raycastHit.collider.transform == player)
{
gameEnding.CaughtPlayer();
}
}
}
}
}
And this is the GameEnding script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameEnding : MonoBehaviour
{
public float fadeDuration = 1f;
public float displayImageDuration = 1f;
public GameObject player;
public CanvasGroup exitBackgroundImageCanvasGroup;
public CanvasGroup caughtBackgroundImageCanvasGroup;
bool m_IsPlayerAtExit;
bool m_IsPlayerCaught;
float m_Timer;
void OnTriggerEnter(Collider other)
{
if (other.gameObject == player)
{
m_IsPlayerAtExit = true;
}
}
public void CaughtPlayer()
{
m_IsPlayerCaught = true;
}
void Update()
{
if (m_IsPlayerAtExit)
{
EndLevel(exitBackgroundImageCanvasGroup, false);
}
else if (m_IsPlayerCaught)
{
EndLevel(caughtBackgroundImageCanvasGroup, true);
}
}
void EndLevel(CanvasGroup imageCanvasGroup, bool doRestart)
{
m_Timer += Time.deltaTime;
imageCanvasGroup.alpha = m_Timer / fadeDuration;
if (m_Timer > fadeDuration + displayImageDuration)
{
if (doRestart)
{
SceneManager.LoadScene(0);
}
else
{
Application.Quit();
}
}
}
}
Back to the unity editor, I set the variables (player, gameending, exitimagebackground and caught imagebackground.
Does anybody know what the problem is and could help me out?
Thank you!
Edit:
these are the components of the Player Character:
and these of the Gargoyle:
Which has these as children:
which have these other components:
On your Observer class,
void OnTriggerEvent(Collider other)
{
if (other.transform == player)
{
m_IsPlayerInRange = true;
}
}
The function name is OnTriggerEvent(Collider), it should be OnTrigger**Enter**(Collider) instead.
Otherwise, it should work as intended.

AddForce doesn't work in Unity

I have the following script
public class SpeedUp : MonoBehaviour {
public Rigidbody2D ball;
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Ball") {
ball.AddForce(Vector2.left * 1000f);
Debug.Log("ABC");
}
}
}
and every time I run my game, the Debug.Log("ABC") prints ABC in the console, but the Rigidbody doesn't move, it stays as it is. Can someone explain me why, because I don't understand why does the console print work and the Rigidbody doesn't move
This is the code for the Ball
public class Ball : MonoBehaviour {
public Rigidbody2D rb;
public Rigidbody2D hook;
public float releaseTime = 0.15f;
private bool isPressed = false;
void Update()
{
if (isPressed)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Vector3.Distance(mousePos, hook.position) > 2.5f)
{
rb.position = hook.position + (mousePos - hook.position).normalized * 2.5f;
}
else
{
rb.position = mousePos;
}
}
}
void OnMouseDown()
{
isPressed = true;
rb.isKinematic = true;
}
void OnMouseUp()
{
isPressed = false;
rb.isKinematic = false;
StartCoroutine(Release());
}
IEnumerator Release()
{
yield return new WaitForSeconds(releaseTime);
GetComponent<SpringJoint2D>().enabled = false;
this.enabled = false;
}
}
The Rigidbody doesn't move may be it's need to getComponenrt()
So, add void Start() method in your the script
public class SpeedUp : MonoBehaviour {
public Rigidbody2D ball;
void Start()
{
ball = ball.GetComponent<Rigidbody2D>();
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Ball") {
ball.AddForce(Vector2.left * 1000f);
Debug.Log("ABC");
}
}
}

Categories