I'm new to Unity and I was wondering if anyone knows how to make the player pick up a weapon and shoot it in Unity 2D. I have already made the sprite for the gun and I've been trying to pick it up with this code:
public GameObject player;
void Update() {
void OnTriggerEnter2D(Collider2D col) {
if (col.tag == "Player") {
gameObject.transform.position = new Vector3(player.transform.position.x + 2, player.transform.position.y, player.transform.position.z);
}
}
}
The gun is set as a trigger and has no rigidbody. All the youtube tutorials show how to pick up an object and then destroys it, but don't show how to "hold" the object.
If you do player.transform.position.x + 2, that sets the gun to the x position of the player + 2. This is not a good way of doing it.
My advice is to do it this way instead.
Copy the gun.
Parent the copy to the camera
Place the gun somewhere on your player.
Disable the gun
In your player script add this line
public GameObject weapon;
Now, in your weapon pickup script, change the player reference to whatever your player script is called instead of a GameObject.
For example, lets assume your player script is called PlayerScript.cs, instead of
public GameObject player;
You should do
public PlayerScript player;
Now, we have a reference to the player script. We can now access the weapon.
Change the OnTrigger to the following:
void OnTriggerEnter2D(Collider2D col) {
if (col.tag == "Player") {
// Set the weapon active
player.weapon.SetActive(true);
// Destroy this pick-up
Destroy(gameObject);
}
}
Also, in your code you have ontriggerenter inside the update method. That is not how it works. Make sure the method is outside of the update method.
Now when you touch the gun on the floor. It should now enable the gun in the players hand and destroy the one on the floor.
In the editor, drag the players gun to the weapon field in the player script.
Also, drag the player to the player field of the gun on the ground.
Hope this helps, feel free to ask more questions if this doesn't work. Keep us updated. :)
Related
I'm making a function that it switches 2 scenes.
When the player enters the trigger, automatically unity switches the scene and in the "Scene view", the player is there, as I wanted. But in the game view, the player dissappears, I don't know why.
I tried to remove a script that it's function is teleport the player to a specific point of the new scene, and it worked.
But obviously I don't want that, because unity automatically teleports the player to a random point, how can I fix that?
Here are the scripts:
TeleportScript:
public class EnterScene : MonoBehaviour
{
public string transitionName; //Also 1-1
void Start()
{
if (transitionName == PlayerController.sharedInstance.areaTransitionName)
{
PlayerController.sharedInstance.transform.position = transform.position; //Moves the player to GameObject position
}
}
// Update is called once per frame
void Update()
{
}
}
https://pastebin.com/jdSPhR3s <-----SceneLoader
https://pastebin.com/KcwHVBfQ <----PlayerController
And a screenshot of my problem:
Problem
I'm making a Unity game, in which player should push all "Enemy" object from the plane. So to be able to count the number of fallen objects I want to generally be able to tell when a collision occurred between the red cube and every other cube. The script seems to not detect a collision, how to fix it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collide : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy")
Destroy(gameObject);
Debug.Log("Hit Occured");
}
}
you need OnCollisionEnter
void OnCollisionEnter(Collision collision){
}
because your colliders aren't triggers.
You need to implement OnCollisionEnter(Collision collision) not OnTriggerEnter(Collider other) or check BoxCollider IsTrigger checkbox
There are 3 things to be checked
1. The OnCollisionEnter should be used in place of OnTriggerEnter
2. isTrigger checkbox should be enabled so that the event is triggered when the both bodies collide with other .
3. The most important thing which no one has mentioned is the tags given to the gameobject or the enemies because we need to define the gameobject that event should be triggered when hit to the specific body because the gameobject contains the collider and can collide to any wall or something so you need to define the tags properly
I try to create a VR scene in unity using google cardboard sdk. I add a cube and CardboardMain.prefab to scene. There is an example scene that detect focus on cube. Its hierarchy view is :
I don't know how to add GUIReticle object or prefab like as the image.
How can I detect focus on an object?
Actually you could make the script by your own and it is quite simple.
You could detect whether the user is looking at your object or not by using RayCast from the Main Camera. If the RayCast hit your object, then it is being focused on.
For example:
using UnityEngine;
using System;
[RequireComponent(typeof(Collider))]
public class LookableObject : MonoBehaviour {
[SerializeField]
Transform cam; // This is the main camera.
// You can alternately use Camera.main if you've tagged it as MainCamera
bool focus; // True if focused
Collider gazeArea; // Your object's collider
public void Start () {
gazeArea = GetComponent<Collider> ();
}
public void Update () {
RaycastHit hit;
if (Physics.Raycast (cam.position, cam.forward, out hit, 1000f)) {
focus = (hit.collider == gazeArea);
} else {
focus = false;
}
}
}
Edit: This is just an example. You probably would want to make a script to do the Raycast only just once instead of doing the Raycast on each of your object over and over again to make your project runs faster.
I am have some difficulty with what is probably a very silly thing. I have an enemy gameobject that depending on where it is hit (collision) - either it, or the play dies. I think the simplest way to describe this is by using the classic Super Mario Bros. game as an example.
As you all know, if the player runs into the enemy - the player will lose - UNLESS he jumps on top of the enemy's head, in which case the enemy should die.
My initial idea was to create two colliders on the gameobject:
Blue border represents a BoxCollider2D - that if collided with - will cause player to lose (notice it is slightly lower from the top)
Green border represents a BoxCollider2D on a child gameobject - that if collided with - will cause the gameobject to die.
The following is a simplified version of the code I used:
// Collider #1
public void OnCollisionEnter2D(Collision2D collision)
{
// Trigger 'Game-Over' logic
}
// Collider #2
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
Destroy(this.gameObject);
}
}
This kind-of works, however momentarily after colliding with Collider #1, Collider #2 is also trigger - and while the enemy is destroyed, the player also loses.
I have been playing with the RigidBody2D values to prevent the player from entering the 2nd collider when hitting the enemy from the top - but apparently with that force / speed, the colliders may be slightly inaccurate (or maybe I'm just doing it wrong?).
I have looked into RayCasts but this seems too complex for something that me appears rather trivial (casting rays on all four sides and four vertices of the player - assuming that the player has a box collider).
What I have resorted to 'for the moment' is a a single collider with a simple piece of code that I am unhappy with, and doesn't always work:
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
float yVelocity = collision.gameObject.transform.rigidbody2D.velocity.y;
if (yVelocity < 0)
{
Debug.Log("Enemy will lose..." + yVelocity);
Destroy(this.gameObject);
}
else
{
// Trigger 'Game-Over' logic
}
}
}
I'm currently working in 2D mode, but solutions for 3D mode (while maybe more complicated than necessary for my question) will also be considered.
Thanks guys.
as a game developer you always have many ways to solve a problem or make a gameplay.
first of all i have to say you should make a polygon collider 2d fo you objects and chracters. just colliding pictures is not very good as i see you used box cilliders in your game.
a good choice can be that you attach and empty object ot you player and set its position under foots of you player and check of enemy hit that enemy dies else if enemy hit main character object, player dies.
another choice can be when o objects collide check y position of 2 objects. of player was higher he kiils, else enemy kills the player.
if you think more you will find more answers.
you have to examin diffrent ways and find most efficient.
I think it will be easy to disable the other collider when one is triggered. You can easily enable/disable colliders with collider.enabled = true; or collider.enabled = false;
// Collider #1
public void OnCollisionEnter2D(Collision2D collision)
{
// Trigger 'Game-Over' logic
// collider2.enabled = false;
}
// Collider #2
public void OnCollisionEnter2D(Collision2D collision)
{
// collider1.enabled = false;
if (collision.gameObject.tag == "Player")
{
Destroy(this.gameObject);
}
}
This way it will be pretty lightweight and easy to implement.
One way of implementing what you want is to put each collider in its child own game object and use the IsTouching() method.
void OnTriggerEnter2D(Collider2D other){
if(GameObject.Find("Top Trigger").GetComponent<BoxCollider2D>().IsTouching(other)){
Destroy(transform.gameObject)
}
if(GameObject.Find("Bottom Trigger").GetComponent<BoxCollider2D>().IsTouching(other)){
Destroy(other.gameObject)
}
}
I am instantiating enemy(Clones) from an enemy GameObject in Unity using c#. I have written a destroy function to delete only the enemy(Clones) when the bullet hits them. Unity renders the enemy GameObject on screen.
I cannot destroy this GameObject in runtime since unity will not instantiate any more enemy(Clones). Please help me not render the base enemy GameObject as it serves no purpose on screen.
Note: Enemy is scripted to walk towards player position and hence keeping the object outside the screen is pointless.
Please Help
here is a snippet of my code. I dragged the enemy GameObject into the Project section. Now it has created 2 Enemy objects on screen
public Rigidbody2D enemy;
void enemySpawn()
{
Rigidbody2D enemyInstance;
enemyInstance = Instantiate(enemy, new Vector3(Random.Range (2,8), Random.Range (-4,4), 0), Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
}
Make your enemy into prefab this can be done by dragging the gameObject into projectview.
You can instantiate new enemies from the prefabs with any gameObject. For example an empty one without any rendering components.
Instantiate can be done with this kind of script:
public GameObject enemy;
void InstantiateEnemy () {
GameObject enemyClone= (GameObject) Instantiate(enemy, transform.position, transform.rotation);
}
Just set the public GameObject in the editor and call the InstantiateEnemy function from somewhere.