i have a program code on a Player model with Nav Mesh Agent that allows it to walk around the world when clicked but am trying to make it jump and haven't seem to achieve it.
this is my code, don't know what to add or remove
public class WorldInteraction : MonoBehaviour {
NavMeshAgent playerAgent;
// Use this for initialization
void Start () {
playerAgent = GetComponent<NavMeshAgent> (); //instantiate the nav mesh to PlayerAgent
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject ()) //condition if the postion is being clicked on a UI is veung clicked
{
GetInteraction (); //call interaction method
}
if (Input.GetMouseButtonDown (1) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject ())
{
transform.Translate (Vector3.up);
}
}
void GetInteraction(){ //this method gets the ray or point clicked and move the player to that point
Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition); //get the point clicked in the world
RaycastHit interactionInfo; //keeps track of the point clicked
if (Physics.Raycast (interactionRay, out interactionInfo, Mathf.Infinity)) //get the point clicked, store it in InteractionInfo and make sure its not out of range by mathf
{
GameObject interactedObject = interactionInfo.collider.gameObject;
if (interactedObject.tag == "Interactable Item") //check if the item point selected is interacrable(cant be move over)
{
interactedObject.GetComponent<Interactable> ().MoveToInteraction (playerAgent); //move playerAgent to the Interactable item, so they could interact(its calling the movetoInteractable method in Interactable class).
} else {
playerAgent.stoppingDistance = 0;
playerAgent.destination = interactionInfo.point; //if its a movable point, player destination is set to that point
}
}
}
}
The NavMeshAgent controls the object in all directions so it will just override your attempt to jump. Make the object with the NavMeshAgent a child of an empty object and just Translate the empty object upwards. Hopefully that helps.
Related
I'm making a mobile game where there is a simple circle with a handle attached to it, it can be controlled and can be rotated with mouse position, I'm using below code for handle control.
public class Controller : MonoBehaviour
{
private float m_force = 0.04f;
// amount of force for the player (circle and handle both)
public GameObject firePoint; // It is the tip of the handle which will shoot bullets
public float senstivity = 1f;
// senstivity control
public void ControlSenstivity(float index)
{
senstivity = index;
}
void Update()
{
//Get the Screen positions of the object
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position) ;
//Get the Screen position of the mouse
Vector2 mouseOnScreen = Camera.main.ScreenToViewportPoint(Input.mousePosition) ;
//Get the angle between the two points
float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen) ;
// it will control the rotation of player (circle and handle both)
transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle) * senstivity);
}
float AngleBetweenTwoPoints(Vector3 a, Vector3 b)
{
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg ;
}
// Below function for adding force to the player (both the circle and the handle), this function I added for mobile input whenever the button is pressed
public void AddForce()
{
transform.Translate(-firePoint.transform.localPosition.x, 0, 0 * m_force);
}
}
In this mobile game the user can rotate the player by dragging on the screen and can move the player by exerting force in the opposite direction of fire point whenever the add force button is pressed but the problem is that whenever I press the button the player takes Input.mousePosition of that button position and get rotated towards the button, that's why it will always move in one direction that is opposite of button. I wanted to know what can I do to not get Input.mousePosition of button which is in the canvas and can originally get position only of camera space. Any response will be appreciated, Thanks in advance!
You can use EventSystem.IsPointerOverGameObject. This method will check if your pointer(mouse/joystick) is on any of the UI elements.
Add if condition before getting mouse position.
// This will ignore all UI game objects
if (!EventSystem.current.IsPointerOverGameObject())
{
//Get the Screen positions of the object
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);
}
I have a "Start Game" button
public static bool GameIsStart;
public void changeCamera ()
{
if (GameIsStart == true)
return;
GameIsStart = true;
SceneManager.LoadScene ("Game");
}
}
``
There is a script that I added to the Prefabs
public GameObject [] gameobject;
private bool gameobject_IS_Spawn;
private float RandomPositionforX;
private int RandomObjects;
private void Update ()
{
if (StartGame.GameIsStart &&! gameobject_IS_Spawn)
{
StartCoroutine (Spawngameobject ());
gameobject_IS_Spawn = true;
}
}
IEnumerator Spawngameobject ()
{
while (true)
{
if (StartGame.GameIsStart)
{
yield return new WaitForSeconds (1.3f);
RandomPositionforX = Random.Range (-2.28f, 2.28f);
RandomObjects = Random.Range (0, gameobject.Length);
Instantiate (gameobject [RandomObjects], new Vector2 (RandomPositionforX, 24f), Quaternion.identity);
}
}
}
}
There is a button on the "Game" scene to access the preview
public void ChangeScene ()
{
SceneManager.LoadScene ("preview");
}
}
I click on the button, the "Preview" scene is loaded, but the "Start game" button does not work.
If I put in the "Preview" button SceneManager.LoadScene ("Game")
then I restart the scene ("Game") and everything works.
But if SceneManager.LoadScene ("Preview") but the buttons don't work.
When switching between scenes, is it necessary to stop Coroutine
How can this problem be corrected?
Without seeing the code it's a bit harder to find where the problem is coming from.
The only thing that is coming to my mind is that it may be something related with how the scene is stored and loaded after.
According to the Scene Manager Documentation, you could save the scene1 in a variable and keep the DontDestroyOnLoad(scene1) on its awake method, then add something like:
Scene scene2 = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene1); To the button that reloads the previous scene.
When I hit the enemy(which has the navMeshAgent) with my player the enemy is sent to the corner of the map and fidgets. It is sent in the direction that the player pushes it in. I just want it to go to the player for now.
The code
{
GameObject playerPosition;
NavMeshAgent navMesh;
// Start is called before the first frame update
void Start()
{
playerPosition = GameObject.FindGameObjectWithTag("Player");
navMesh = GetComponent<NavMeshAgent>();
if(navMesh == null)
{
Debug.Log("Nav Mesh for enemy brock");
}
}
private void Update()
{
Vector3 dir = playerPosition.transform.position;
navMesh.destination = dir;
}
}
This is what it looks like
I've made a 3d game and I have a first person controller, control by a joystick. I want my player to shoot only when I touch a button on the screen, but now my player shoots if I touch anything on the screen. This is the script for the shoot function:
using UnityEngine;
using UnityEngine.UI;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public Button button;
// Start is called before the first frame update
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
button.onClick.AddListener(TaskOnClick);
}
// Update is called once per frame
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
}
void Shoot()
{
RaycastHit hit;
if( Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(damage);
}
}
}
void OnCollisionEnter(Collision collision)
{
Debug.DrawRay(collision.contacts[0].point, collision.contacts[0].normal, Color.green, 2, false);
}
void TaskOnClick()
{
Shoot();
}
}
Your Shoot() method runs whenever you press the "Fire1" button, since the only check you are doing is if (Input.GetButtonDown("Fire1")).
If you want to depend on a button to fire you need to take this part of the code out and call Shoot() whenever you click the button.
You can add the event to the button using code, as explained here
public Button m_YourFirstButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
m_YourFirstButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
//Output this to console when Button1 or Button3 is clicked
Debug.Log("You have clicked the button!");
}
or you could call it from the inspector by referencing your Gun monobehaviour.
With 8th Wall XR is it possible to click on a surface and make it the active surface and place a gameobject on the position of the click? Kinda like ARKit which only augments the gameobject after clicking on it.
Something like this should do the trick. You'll need a GameObject (i.e. a Plane) with an XRSurfaceController attached, and put it on a Layer called "Surface":
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaceObject : MonoBehaviour {
// Adjust this if the transform isn't at the bottom edge of the object
public float heightAdjustment = 0.0f;
// Prefab to instantiate. If null, the script will instantiate a Cube
public GameObject prefab;
// Scale factor for instantiated GameObject
public float objectScale = 1.0f;
private GameObject myObj;
void Update() {
// Tap to place
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began ) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
// The "Surface" GameObject with an XRSurfaceController attached should be on layer "Surface"
// If tap hits surface, place object on surface
if(Physics.Raycast(ray, out hit, 100.0f, LayerMask.GetMask("Surface"))) {
CreateObject(new Vector3(hit.point.x, hit.point.y + heightAdjustment, hit.point.z));
}
}
}
void CreateObject(Vector3 v) {
// If prefab is specified, Instantiate() it, otherwise, place a Cube
if (prefab) {
myObj = GameObject.Instantiate(prefab);
} else {
myObj = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
myObj.transform.position = v;
myObj.transform.localScale = new Vector3(objectScale, objectScale, objectScale);
}
}