I want to set my PS4 controller R2 trigger to shoot bullets in the VR game i am making for google cardboard.
I have paired the controller to the phone and i am already using it to move around and jump with the FPSController Asset and i made a shooting script
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
public class Firing : MonoBehaviour
{
//Drag in the Bullet Emitter from the Component Inspector.
public GameObject Bullet_Emitter;
//Drag in the Bullet Prefab from the Component Inspector.
public GameObject Sphere;
//Enter the Speed of the Bullet from the Component Inspector.
public float Bullet_Forward_Force;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("joystick button 0"))
{
//The Bullet instantiation happens here.
GameObject Temporary_Bullet_Handler;
Temporary_Bullet_Handler = Instantiate(Sphere, Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation) as GameObject;
//Sometimes bullets may appear rotated incorrectly due to the way its pivot was set from the original modeling package.
//This is EASILY corrected here, you might have to rotate it from a different axis and or angle based on your particular mesh.
Temporary_Bullet_Handler.transform.Rotate(Vector3.left * 90);
//Retrieve the Rigidbody component from the instantiated Bullet and control it.
Rigidbody Temporary_RigidBody;
Temporary_RigidBody = Temporary_Bullet_Handler.GetComponent<Rigidbody>();
//Tell the bullet to be "pushed" forward by an amount set by Bullet_Forward_Force.
Temporary_RigidBody.AddForce(transform.forward * Bullet_Forward_Force);
//Basic Clean Up, set the Bullets to self destruct after 10 Seconds, I am being VERY generous here, normally 3 seconds is plenty.
Destroy(Temporary_Bullet_Handler, 3.0f);
}
}
}
I want to boot the "game" on the phone and to press R2 to shoot the bullets
Related
It has two camera angles. First person for engaging gameplay and top-down for 2D game experience. But in top down camera view I can't figure out the rotation of the camera with respect to player.
I wrote the following script for the main(top-down) camera view.
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
private Vector3 offset = new Vector3(0f, 24.953f, -0f);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}`
I tried
transform.rotation = player.transform.rotation;
but it didn't work since camera is on top of player. If I could somehow do
transform.rotation = player.transform.rotation + X axis 90 degree;
That would be perfect but I don't know how to do that.
If I understand you correctly, you want to follow the player from above with your second camera. Leaving some flexibility, the best option I think would be Unity's built in Transform.LookAt(target) method (LookAt), which automatically rotates an object (in your case the camera) so that it faces the target.
Therefore, you could do something like this in your Update, assuming your script is attached to the Camera. Otherwise substitute transform with Camera.main.transform:
transform.LookAt(player);
Note: If you plan to have your camera fixed above your player at all times, it is sufficient if you perform the LookAt once, e.g. in Start and then attach the camera as a child to the player. If your camera does not move with your player in the world but you want it to focus the player anyway, do do it in Update. Hope I addressed your problem:)
My problem has been resolved. I was trying to rotate the wrong axis. My bad.
mouseInput = Input.GetAxis("Mouse X");
transform.Rotate(Vector3.forward * speed * -mouseInput);
I needed to get mouse input from user and change the Z-axis according to it. Game is working fine now.
I’m making a small shooter for two players, everyone can shoot. The problem is that when a bullet flies at high speed, then there are certain zones in its trajectory in which it does not touch the object, and accordingly OnTriggerEnter2d does not work there. Here is the bullet flight script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet: MonoBehaviour
{
Rigidbody2d rb;
public int Player;
public float speed = 0.4f;
public Vector3 mode; // Direction of the bullet (Vector3.left, right)
// Start is called before the first frame update
void Start ()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate ()
{
rb.velocity = mode * speed;
}
}
High speed physics is always a hard nut to crack. Like Iggy mentions you can/should use continuous collision detection.
If you still have issues and still want fast projectiles it get harder. Here are some options.
You can lower the physics time step in time settings (very expensive not recommended but you can test).
You can make the bullet's colliders dynamically bigger. (Might be the simplest easiest solution). When you spawn bullets, calculate based on their speed how long a box collider should be and dynamically position it behind the bullet sorta like a trail (make sure the bullet has moved forward enough to fully expand so you don't hit things behind the player). The box collider's size should be the same as how much distance it moves every frame. That way after moving a tons in a frame all the positions the bullet has been in the frame will trigger a collision on the box collider. For bullet impact and sfx don't spawn them where the bullet is but at the point of contact.
You can calculate if a collision should have happened. (After the physics update check behind the projectile with like a raycast).
You can do your own physics or hybrid. Unity lets you simulate physics when ever you want manually instead of the normal physics update. With more control over that you could add more calculations for fast moving object.
I would like to use a characters tongue so instead of shooting a bullet, it goes toward the enemy, licks it, and comes back. I got this wording from this question: Unity shooting with Tongue 2d game (hasn't been answered and is 4+ years old). The only difference is my character moves.
I have this code from looking at a shooting tutorial so when you click the tongue prefab generates and is at the correct angle. I need it to grow on click and shrink back.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineController : MonoBehaviour
{
public GameObject player;
private Vector3 target;
public GameObject crosshairs;
public GameObject tonguePrefab;
// Start is called before the first frame update
void Start()
{
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
crosshairs.transform.position = new Vector2(target.x, target.y);
Vector3 difference = target - player.transform.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
if (Input.GetMouseButtonDown(0))
{
shootTongue(rotationZ);
}
}
IEnumerator shootTongue(float rotationZ)
{
GameObject t = Instantiate(tonguePrefab) as GameObject;
t.transform.position = new Vector2(target.x, target.y);
t.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
yield return new WaitForSeconds(2000);
t.SetActive(false);
}
}
I was also trying to make it disappear after whatever time and with that it doesn't work at all?
If the prefab is just a line with a simple texture I suggest using a line renderer:
Create an empty transform that starts on the mouth and then it move untill it reaches the crosshair. The movement is done using Vector2.MoveTowards.
Your tongue will no be a line renderer component. This line renderer will have 2 points, the start which is static, and the end which you have to update on the Update() for example, to correspond to the positions of the empty transform in item 1.
If you really wish to expand a tongue gameobject instead, then you are going to need a bit of math, this answer has what you need but in 3D:
https://answers.unity.com/questions/473076/scaling-in-the-forward-direction.html
1) I suggest creating sprite/sprite sheet animations with Mecanim or relatively new Skeletal Animation with Anima2D. With these systems you can create nice animations, transitions, even animate the sphere collider to trigger collisions and actions, change active state of your objects, etc. and control the animation with very little code. This way you can get best effects in my opinion.
As tongue is not a bullet... :) You only need one. I don't think you want to Instantiate/Create prefabs every time you press the lick button. Instead you should just turn your tongue object on/off (gameObject.SetActive). You can also change your object active state within the animation. So if you don't know how to code it you can do most of it in the Animation window and use very simple code to play the animation when you press the lick button. Whenever a sphere collider touches something you can tell the Animator Controller to play a 'roll back' animation and it will transition nicely to the start position.
There are many tutorials about Mecanim, Animations, 2D Animations, Anima2D, Animator Controller out there.
2) If you need very good control over the tongue you could create a custom mesh and control it via script but this is far more difficult.
3) The reason why your object is not turning off is probably because you wrote WaitForSeconds(2000) so it will turn off after 2000 seconds - more than half an hour. You should also call it with StartCoroutine(shootTongue()) as it is a Coroutine. Again if you want to turn off the object don't create new ones every time. If you want to keep creating new objects you should Destroy the objects instead. Otherwise you will end up with a lot of deactivated tongues in your scene and I don't think you needs that many tongues.
Versions: Unity v2019.2.4f1, Oculus Utilities v1.41.0, OVRPlugin v1.41.0, SDK v1.42.0
I am in the process of creating an Oculus Rift game where the player can use buttons to toggle between walking around on the ground and looking around in a bird's eye view of the environment. To accomplish this, I am using the following script to toggle between two different OVRPlayerControllers, one positioned on the ground and one positioned in the air looking down:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraSwitcher : MonoBehaviour
{
public GameObject firstPersonCameraPrefab;
public GameObject overheadCameraPrefab;
void Update()
{
bool isDownOne = false;
bool isDownThree = false;
isDownOne = OVRInput.GetDown(OVRInput.Button.One);
isDownThree = OVRInput.GetDown(OVRInput.Button.Three);
if (isDownOne || isDownThree)
{
switchCam();
}
}
public void switchCam()
{
overheadCameraPrefab.SetActive(!overheadCameraPrefab.activeInHierarchy);
firstPersonCameraPrefab.SetActive(!firstPersonCameraPrefab.activeInHierarchy);
}
}
At the start of the game, the first person player is active, and the overhead player is not active. When I use this script, the headset toggles between looking through the two cameras. However, the connection between the game and the movement controls on the controllers gets severed after the first switch. When I toggle back down to the ground, I can no longer use my controllers to move my player around.
How can I switch between players and keep the movement controls in tact?
This is because you have more than 1 OVRManager in your scene, the prefab OVRCameraRig has 1 attached, so if you have more than one of this prefabs, like 2 players, Oculus won't work correctly.
Put the component in an empty prefab that never turns off, and set switch between your player controllers freely.
First, I know that this question has been asked a lot, but I cant find a solution, so mi problem is, Im making an educational game, and I have a vein and the blood flow (with many box colliders) and a single blood cell (also with a box collider) however i want the cell to destroy when it reaches the wall collider, but it doesn't it just stays there, here is the project!
http://tinypic.com/r/10706es/9
(cant upload images because of my reputation, sorry)
The collider where I want to destroy my cell is the pink collider, however when it touches it it just does nothing, here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionEnter(Collision col)
{
print("hihi");
if (col.gameObject.tag == "Collider")
{
Destroy(gameObject);
}
}
}
Also, here is the AddForce script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForce : MonoBehaviour {
public float thrust;
public Rigidbody rb;
private Vector3 up;
private bool move;
void Start()
{
rb = GetComponent<Rigidbody>();
up = new Vector3(0, 1, 0);
move = false;
}
void FixedUpdate()
{
if (Input.GetKey("space"))
{
if (rb.velocity.magnitude < 5)
rb.AddForce(up * thrust);
move = true;
}
else
{
if (move == true)
rb.velocity = new Vector3(0, -0.5F, 0);
}
}
}
thanks for your help guys! :D
It can be several things, whether you are using OnTriggerEnter or OnCollisionEnter:
Missing RigidBody (the most common). At least one of the GameObjects involved needs to have a RigidBody. (check if at least one of them have a RigidBody attached and, if you are using OnCollisionEnter, does not have the "Is Kinematic" checked). See the below collision matrix for more information.
Missing tag. The GameObject from collision does not have a "Collider" tag (try to remove the if statement to test it) (to compare tags, use collider.gameObject.CompareTag("Collider"), it has a better performance)
Undetectable collision. The physics Layer Collision Matrix is set to not detect collision between the layers the objects are (enter Edit > Project > Phisics and check if the encounter of the layer of both GameObjects are checked inside Layer Collision Matrix)
Wrong Collider configuration. one or both of the GameObjects have a small/wrong placed or absent Collider (check if they both have a Collider component and if their size are correct)
If it's working, you should be able to press play and drag one GameObject into the other one and your Debug.Log will appear.
As an advice, use tag names that better describe the group of GameObjects that will be part of it, like "RedCells" or "WhiteCells". It'll be easier to configure the Layer Collision Matrix and improve the performance of your game.
Another advice: for colliders that just destroys another GameObject (don't react, like bump or actually collide) I use triggers. That way, the collision between them will not alter anything in the remaining GameObject (like direction/velocity/etc). To do that, check the Is Trigger in the Collider and use OnTriggerEnter instead of OnCollisionEnter.
Source
some times you added Nav Mesh Agent component to your game object ( to auto route operation in strategic game and ...).
in this case, this game object does not attend to collider.
So, if you really need this Nav Mesh Agent, you should add Nav Mesh Obstacle to other fixed game object and also add Nav Mesh Agent to other movable game object.
I have a few followup questions which might lead to a solution.
First, does the object holding your 'collision' script have a rigidbody and a collider on it?
Second, does the wall have both a rigidbody and collider?
Usually if those conditions are met, then collisions will work.
A couple other things that could be the problem:
Check if you have istrigger checked for either object and make sure it is unchecked.
Check and make sure the rigidbodies on both are non-kinematic.
I've finally fixed it, I dont really know if this was the problem, but i just removed the rigidbody from the parent of the wall and it started working!, I dont know what the rigidbody did, but just with that the problem was fixed, thank you all for your help! :D
Ensure the following things are considered in your code,
All gameobject should contain collider attached and the player
gameobject should contain the rigidbody component in it.
The collider size should change to the width and height of the
component instead of default (1,1) values.