I'm trying to create a platform that will move player with itself. Both horizontally, as well as vertically. I tried to do this by setting the player's parent to be the platform, but the player doesn't stick to it. This is the code I'm trying to use:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platform : MonoBehaviour
{
public GameObject player;
public GameObject platformAnchor;
public float movementSpeed;
void Update()
{
transform.position = Vector3.Lerp(transform.position, platformAnchor.transform.position, (Time.deltaTime * movementSpeed));
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == player)
{
other.transform.parent = transform;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject == player)
{
other.transform.parent = null;
}
}
}
Related
I am making a game similar to flappy bird I am currently following this guy's tutorial and I'm stuck near the end I have been searching for 4hours and can't find a solution here's the code
Game Manager:
using UnityEngine;
public class GameManager : MonoBehaviour
{
private int score;
public void GameOver()
{
Debug.Log("Game Over!");
}
public void IncreaseScore()
{
score++;
}
}
player:
using UnityEngine;
public class playermove : MonoBehaviour
{
private Vector3 direction;
public float gravity = -9.8f;
public float strength = 5f;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
{
direction = Vector3.up * strength;
}
direction.y += gravity * Time.deltaTime;
transform.position += direction * Time.deltaTime;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Obstacle")
{
FindObjectOfType<GameManager>().GameOver();
} else if (other.gameObject.tag == "Score")
{
FindObjectOfType<GameManager>().IncreaseScore();
}
}
}
I'm trying to detect when the player hits a sprite with a tag and 2d collider (set as a trigger)
edit: Inspector ss of trigger object
In Unity I Wrote a code to make a collider sphere that detects an enemy if detected it will go to the enemy but when I run the code it only look at the enemy.
Is there any solution to this problem? it will be greatly appreciated
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class choclatemilkscirpt : MonoBehaviour
{
NavMeshAgent Agent;
public Patrol patrol;
public Transform MilkSpawner;
public bool chasing;
public Transform[] Points;
[SerializeField]
LayerMask layermask;
public Transform[] Samurais;
public Transform view;
public Transform Point;
public float raydistance = 10f;
public Attack1 attack;
public takingdamage enemyhealth;
public float LookRadius = 10f;
public Transform[] Milk;
public Transform point;
public float enemyview = 5f;
// Start is called before the first frame update
void Start()
{
Agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
Collider[] collider = Physics.OverlapSphere(point.transform.position, LookRadius);
foreach(Collider troops in collider)
{
Debug.Log(transform.name);
if(troops.transform.tag == "Milk")
{
Chaseing(troops.transform);
}
}
void Chaseing(Transform target)
{
Agent.SetDestination(target.position);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(point.transform.position, LookRadius);
}
public void ChasePlayer(Transform target)
{
Agent.SetDestination(target.position);
transform.LookAt(target.position);
}
public void resetView()
{
transform.LookAt(view);
}
void GettingtoGoal()
{
Agent.SetDestination(MilkSpawner.transform.position);
}
}
I try to expand the NavMesh Agent radius, and lift the offset up a bit bit it did not work
I'm developing a TopDown 2D game in Unity.
The idea is, when the player steps on a certain tile, a UI with text pops up (already working) and the player stops moving until the player clicks a button (already programmed and working) and the UI disappears.
I was advised to turn the RigidBody2D to kinematic however it doesn't work and it just does what it used to do.
Am I doing something wrong?
Here is the code for the trigger script on the tiles:
public class TriggerScript : MonoBehaviour
{
public string popUp;
public void Start()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
Rigidbody2D Player = GameObject.Find("Player").GetComponent<Rigidbody2D>();
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
if (collision.gameObject.tag == "Player")
{
pop.PopUp(popUp);
Player.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
Rigidbody2D Player = GameObject.Find("Player").GetComponent<Rigidbody2D>();
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.closeBox();
Player.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
}
}
PopUpSystem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator popupanimation;
public TMP_Text popUpText;
public PLayerController mb;
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text;
popupanimation.SetTrigger("pop");
}
public void closeBox()
{
popupanimation.SetTrigger("close");
mb.camMove = true;
}
}
PLayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PLayerController : MonoBehaviour
{
private Rigidbody2D MyRB;
private Animator myAnim;
[SerializeField]
private float speed;
public bool camMove = true;
// Start is called before the first frame update
void Start()
{
MyRB = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (camMove)
{
MyRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
myAnim.SetFloat("moveX", MyRB.velocity.x);
myAnim.SetFloat("moveY", MyRB.velocity.y);
if ((Input.GetAxisRaw("Horizontal") == 1) || (Input.GetAxisRaw("Horizontal") == -1) || (Input.GetAxisRaw("Vertical") == 1) || (Input.GetAxisRaw("Vertical") == -1))
{
myAnim.SetFloat("LastMoveX", Input.GetAxisRaw("Horizontal"));
myAnim.SetFloat("LastMoveY", Input.GetAxisRaw("Vertical"));
}
}
if (!camMove)
{
MyRB.velocity = new Vector2(0, 0);
}
}
}
TriggerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerScript : MonoBehaviour
{
public string popUp;
Animator popAnim;
public PLayerController mb;
private void Start()
{
popAnim = GameObject.FindGameObjectWithTag("PopUpBox").GetComponent<Animator>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
var myp = GameObject.FindGameObjectWithTag("Player").GetComponent<PLayerController>();
if (collision.gameObject.tag == "Player")
{
pop.PopUp(popUp);
mb.camMove = false;
}
if (popAnim.GetCurrentAnimatorStateInfo(1).IsName("close"))
{
mb.camMove = true;
Debug.Log("close");
}
}
private void OnTriggerExit2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.closeBox();
}
}
Things to keep in mind:
1- Make a new tag and call it PopUpBox. then assign this tag to the Trigger GameObject.
2- To the button of the PopUpBox GameObject (the one which is disabled) assign GameManager GameObject and in its function select PopUpSystem.closeBox
3- In both Trigger GameObject and GameManager assign Player in Mb field.
Hope this help you. You can play with that more to get better results.
I am creating this flappy bird style game in unity with C#.
I have a scored function in the Game Controller script. Here it is...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
private int score = 0;
public float starScrollSpeed;
public float groundScrollSpeed;
public float skyScrollSpeed;
public GameObject gameOverText;
public GameObject playAgain;
public bool gameOver = false;
public static GameController instance;
public Text scoreText;
// Start is called before the first frame update
void Awake()
{
if(instance == null)
{
instance = this;
}
else if(instance != this)
{
Destroy(gameObject);
}
}
// Update is called once per frame
void Start()
{
}
void Update()
{
}
public void BirdScored()
{
if (gameOver)
{
return;
}
score++;
scoreText.text = "SCORE " + score.ToString();
}
public void PlaneDestroyed()
{
gameOverText.SetActive(true);
playAgain.SetActive(true);
gameOver = true;
}
}
Actually Bird and Plane is the same thing.
What I want to do is to make the bird score/run the BirdScored() function when the Plane overlaps with a star. The Plane has a Rigidbody2D and a collider and stars have a Rigidbody2D but no collider because In the bird script if the plane collide, it destroys.
Here is the Bird Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bird : MonoBehaviour
{
private bool isDead = false;
private Rigidbody2D rb2d;
public float upforce = 200f;
private Animator anim;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (isDead == false)
{
if (Input.GetMouseButtonDown(0))
{
rb2d.velocity = Vector2.zero;
rb2d.AddForce(new Vector2(0, upforce));
}
}
anim.SetTrigger("Flap");
}
void OnCollisionEnter2D()
{
isDead = true;
anim.SetTrigger("Die");
GameController.instance.PlaneDestroyed();
}
}
And here is the star script...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Stars : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.name == "Plane")
{
GameController.instance.BirdScored();
}
}
}
What is wrong and what should I do?
Put a Colider2D on the star, and check the Is Trigger option in the inspector.
The Is Trigger is disable the collision with any other collider2d so your plane wont be destroyed by the OnCollisionEnter2D, but the OnTriggerEnter2D will trigger properly.
I can see in your screenshot that the collider isn't set to "is trigger", which makes it unable to register trigger collisions.
I am trying to make a Magnet power up like subway surfer. My game is a endless runner game. When the runner collide with the magnet, the coins attracting towards the player. But it is not working. After runner collide with the magnet and after that every time he collide with the coin below error keep coming.
NullReferenceException: Object reference not set to an instance of an object
Coin.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Coin.cs:37)
any one can help me?
Magnet Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Magnet : MonoBehaviour
{
// Start is called before the first frame update
public GameObject coinDetectorObj;
public static bool iscoinDetectorObj;
// Start is called before the first frame update
void Start()
{
coinDetectorObj = GameObject.FindGameObjectWithTag("coin detector");
coinDetectorObj.SetActive(false);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
StartCoroutine(ActivateCoin());
Destroy(transform.GetChild(0).gameObject);
}
}
IEnumerator ActivateCoin()
{
coinDetectorObj.SetActive(true);
yield return new WaitForSeconds(0.5f);
coinDetectorObj.SetActive(false);
}
}
Coin Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : MonoBehaviour
{
public Transform playerTransform;
public float moveSpeed = 17f;
CoinMove coinMoveScript;
void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
coinMoveScript = gameObject.GetComponent<CoinMove>();
}
void Update()
{
transform.Rotate(130 * Time.deltaTime, 0, 0);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
FindObjectOfType<AudioManager>().PlaySound("PickUpCoin");
PlayerManager.numberOfCoins += 1;
Destroy(gameObject);
}
if (other.gameObject.tag == "coin detector")
{
coinMoveScript.enabled = true;
}
}
}
CoinMove Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinMove : MonoBehaviour
{
Coin coinScript;
// Start is called before the first frame update
void Start()
{
coinScript = gameObject.GetComponent<Coin>();
}
// Update is called once per frame
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, coinScript.playerTransform.position,
coinScript.moveSpeed * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
//Add count or give points etc etc.
Destroy(gameObject);
}
}
}