Unity 5 How to fire a bullet - c#

I have been working on this code for a while and I just cant seem to figure it out. When I click in the game instead of going to the mouse posistion it throws my bullets far away usually from anywhere to 100 to 300.
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
public GameObject Player;
public GameObject Bullet;
void Update()
{
bool Shot = false;
if(Input.GetMouseDown(0) && Shot == false)
{
Shot = true;
}
if (Shot == true)
{
float x = Player.transform.position.x;
float z = Player.transform.position.z;
Instantiate(Bullet, new Vector3(x, 0.5f, z)), Quaternion.identity);
x = Input.mousePosition.x;
z = Input.mousePosition.z;
}
}
}

This code doesn't make much sense for me; You just instantiate a Gameobject at the last mouse position (which is on you screen, not in the 3D world) and you don't apply any force to it. Please take a look at this thread (you probably want to use the Gun_Physical script).

Related

EnemyAI script not moving the Enemy

I am making my first foray into AI, specifically AI that will follow the player.
I am using the A* Path finding project scripts, but used the Brackeys tutorial for the code
https://www.youtube.com/watch?v=jvtFUfJ6CP8
Source in case needed.
Here's the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class EnemyAI : MonoBehaviour
{
public Transform Target;
public float speed = 200f;
public float NextWayPointDistance = 3f;
Path path;
int currentWaypoint = 0;
bool ReachedEndOfpath = false;
Seeker seeker;
Rigidbody2D rb;
public Transform EnemyGraphics;
// Start is called before the first frame update
void Start()
{
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("UpdatePath", 0f, 1f);
}
void UpdatePath()
{
if (seeker.IsDone())
seeker.StartPath(rb.position, Target.position, OnPathComplete);
}
void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
// Update is called once per frame
void fixedUpdate()
{
if(path == null)
return;
if(currentWaypoint >= path.vectorPath.Count)
{
ReachedEndOfpath = true;
return;
}
else
{
ReachedEndOfpath = false;
}
Vector2 Direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
Vector2 Force = Direction * speed * Time.fixedDeltaTime;
rb.AddForce(Force);
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if(distance < NextWayPointDistance)
{
currentWaypoint++;
}
if(rb.velocity.x >= 0.01f)
{
EnemyGraphics.localScale = new Vector3(-1f, 1f, 1f);
}else if(rb.velocity.x <= 0.01f)
{
EnemyGraphics.localScale = new Vector3(1f, 1f, 1f);
}
}
}
How I tried to fix the issue:
I thought it could've been a problem with the speed so I increased it to 10000000, and still nothing
Next I thought it was a problem with the Rigidbody2d so I check there, found the gravity scale was set at 0, so I increased it to 1. It made my enemy fall to the ground but still no movement.
I thought it could've been a problem with the mass and drag, so I set Linear drag and Angular drag to 0, and also set mass to 1. Still nothing.
I set the body type to kinematic, pressed run, nothing. Set the body type to static, pressed run, nothing. Set the body type to Dynamic, pressed run, still nothing.
I tried to make a new target for the enemy to follow, dragged the empty game object i nto the target, pressed run and still didn't move.
I am at a loss on how to fix this.
Please help?
Looks like maybe a typo? You have:
// Update is called once per frame
void fixedUpdate()
{
but the method is called FixedUpdate(), with a big F in front. You have fixedUpdate, which is NOT the same.

How do I detect if a sprite is overlapping any background sprite?

I want to detect if an empty gameobject is between a sprite which I've drawn and the camera.
Background objects are tagged "Background" and are in the layer "background".
Currently, the Debug.log statement always says "Does not detect background". I've tried switching the direction of the raycast from back to forward several times and that didn't fix it. The gameobject shooting the ray has a z position of -1, the sprite has a z position of 0. The sprite has a 2D box collider on it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomMaker : MonoBehaviour
{
public float speed = 5;
public float distance = 5;
public Transform horse;
public Transform carriage;
void Update()
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
RaycastHit2D backgroundInfo = Physics2D.Raycast(horse.position, Vector3.forward, distance);
if (backgroundInfo)
{
Debug.Log("DETECTSBACKGROUND");
}
else
{
Debug.Log("Does not detect Background");
//it always displays this one, it never displays the other debug.log
}
}
}
Consider using Physics2D.OverlapPointAll instead of a raycast.
This will require that background sprites have Collider2D components on their gameobjects, their gameobjects be tagged Background and be on the background layer.
I advise having the background layer ignore collisions with everything. See the physics 2d options documentation for more information on how to do that.
Here's what the code could look like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomMaker : MonoBehaviour
{
public float speed = 5;
public float distance = 5;
public Transform horse;
public Transform carriage;
void FixedUpdate() // otherwise, visual lag can make for inconsistent collision checking.
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
Collider2D[] cols = Physics2D.OverlapPointAll(
Vector3.Scale(new Vector3(1,1,0), horse.position), // background at z=0
LayerMask.GetMask("background")); // ignore non background layer objects
Collider2D backgroundCol = null;
for (int i = 0 ; i < cols.Length ; i++) // order of increasing z value
{
if (cols[i].tag == "Background") // may be redundant with layer mask
{
backgroundCol = cols[i];
break;
}
}
if (backgroundCol != null)
{
Debug.Log("DETECTSBACKGROUND: " + backgroundCol.name);
}
else
{
Debug.Log("Does not detect Background");
}
}
}
I tested with this setup:

How to shoot ball to Touch X position Unity 3D?

I have a ball on a ground, and when touching the screen I want to shoot it to the X position of the Touch. Do you have any suggestions?
This is the code I have so far:
public Rigidbody Ball;
public float Speed = 50f;
void FixedUpdate () {
if(ClickDone == false){
if (Input.GetMouseButton(0)){
ClickDone = true;
Ball.velocity = transform.forward * Speed;
}
}
}
here is your new code :
using UnityEngine;
public class GoToTouch : MonoBehaviour
{
public Camera cam;//put your main camera here
public float speed;//Speed of movement
Vector3 LastTouch;
void Start()
{
LastTouch = Vector3.zero;
}
void Update()
{
//We check for new touches etch frame
if (Input.touchCount> 0)
LastTouch = Input.touches[0].rawPosition;
//We move towards the last touch
if(LastTouch != Vector3.zero)transform.position=
Vector3.Lerp(transform.position,cam.ScreenToWorldPoint(LastTouch),speed*Time.DeltaTime);
}
}
what is important for you to look at is the
ScreenToWorldPoint function LastTouch holds the actual pixel the user touched
after ScreenToWorldPoint you get the position that the pixel he touched represent in the
world. Good luck learning !

How can I trigger some action once the player is exiting the collider door area?

I want to do two parts with the script:
When the player is exiting a door trigger action.
When the action is tirggered make the npc slowly rotating facing the player and start moving to the player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
public class SpaceshipCutscene : MonoBehaviour
{
public Transform player;
public Transform npc;
public float cutsceneDistance = 5f;
public float speed;
private bool moveNpc = false;
// Use this for initialization
void Start()
{
}
private void Update()
{
if (moveNpc)
{
float travel = Mathf.Abs(speed) * Time.deltaTime;
Vector3 direction = (player.position - npc.position).normalized;
Quaternion lookrotation = Quaternion.LookRotation(direction);
npc.rotation = Quaternion.Slerp(npc.rotation, lookrotation, Time.deltaTime * 5);
Vector3 position = npc.position;
position = Vector3.MoveTowards(position, player.position, travel);
npc.position = position;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.name == "Horizontal_Doors_Kit")
moveNpc = true;
}
}
It's never getting to the moveNpc = true; line.
The player have a Rigidbody.
In the screenshot it's the player inspector. The soldier is not the player !
The player is a first person.
The soldier should rotate slowly facing the player and start moving to the player when the player exit the door.
The script is attached to the Spaceship GameObject:
The door have some childs and this is the one with the box collider:
That's why in the script I'm checking against the Horizontal_Doors_Kit since this doors child have the box collider.
But it's never getting to the line:
moveNpc = true;
I used a break point on this line.
The problem is seems to be at least from my test is that the script with the OnTriggerExit must be attached to the player and not to some empty GameObject ( Spaceship ). Once the script is attached to the player the trigger is working. I thought that the OnTriggerExit can be trigger from any object but it was my mistake.

getting my 2d sprite flip to work depending on a Transform's location from it

So, this code just isn't responding for whatever reason. I have an enemy that I'm trying to get to face the player at all times (The enemy swoops over the player's head back and forth periodically). But other than making a flip happen whenever a timer hits 0, which doesn't really work all that well, I can't get the Flip function to work. I know the Flipper function is fine; I already tested it out and everything. I'm just not sure how to tell the enemy that when the player is to the left of it, to turn, and vice versa.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dragoonDetection : MonoBehaviour {
private Rigidbody2D rb;
private Animator anim;
public Transform Player;
private bool facingRight = true;
void Start ()
{
rb = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
}
void Update()
{
Flip();
}
void Flip()
{
if (Player.transform.localScale.x > 0) {
transform.localScale = new Vector3 (1.69f, 1.54f, 1f);
}
if (Player.transform.localScale.x < 0) {
transform.localScale = new Vector3 (-1.69f, 1.54f, 1f);
}
}
void Flipper()
{
facingRight = !facingRight;
Vector2 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Got any ideas? I'd rather avoid using FindGameObject because it's not actually looking for the player script. It's looking for a child transform with no script attached to the player. And because I have two different player GameObjects that you can switch to anytime in the game, it wouldn't really work for me in that regard.
You will need to perform a check of some sort against the players position with the bird position if you want it to face the player at all times. A barebones method would just be to compare the x-positions of the two objects and change the scale accordingly.
void Update()
{
transform.localScale = new Vector3(getDir()*1.69f, 1.54f, 1);
}
private int getDir()
{
if (player.transform.position.x < transform.position.x)
return -1;
else
return 1;
}
You should throw some additional checks in here to keep it from updating the scale every frame when there is no change.

Categories