Okay so I've been fighting with this script for a couple days now. I've made progress in other aspects but I can't seem to get my enemies to properly chase the player character.
The script is supposed to have the enemies wander until an empty child 'eyes' sees the player. Then it should start chasing the player. Think pac-man. What it's doing right now is making one loop of it's wander cycle and then stopping and not seeing the player at all.
This is the code that I've got so far for that script -
using UnityEngine;
using System.Collections;
public class dudeFollow : MonoBehaviour {
Transform tr_Player;
float f_MoveSpeed = 3.0f;
private DudeMove moveScript;
public Transform eyes;
public float sightRange = 3f;
// Use this for initialization
void Start () {
tr_Player = GameObject.FindGameObjectWithTag("Player").transform;
moveScript = GetComponent<DudeMove>();
}
// Update is called once per frame
void Update () {
RaycastHit hit;
if (Physics.Raycast (eyes.transform.position,eyes.transform.forward, out hit,sightRange) && hit.collider.CompareTag ("Player")) {
transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
moveScript.enabled = false;
}
}
}
Any help or tips would be appreciated.
Because you have 2D game, what most likely happens is your enemy wonders away on z-axis as well, but because it's 2D, you can't see it. So switch to 3D mode in your main scene window and see if that's the case.
If it is, just reset z-axis to 0 on every frame and disable angular momentum :) I had this happen with 2D games.
void Update () {
RaycastHit hit;
if (Physics.Raycast (eyes.transform.position,eyes.transform.forward, out hit,sightRange) && hit.collider.CompareTag ("Player")) {
transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
moveScript.enabled = false;
}
transform.position.z = 0; // or something along those lines, I don't remember the syntax exactly.
}
Related
I have a weird problem and cant seem to fix it. I was creating my first game in Unity and I was testing around a bit after creating a movement system and whenever I touch another object (it doesn't matter if it has a rigid body or not), my player suddenly starts moving on its own. I have a video showing what exactly happens: https://youtu.be/WGrJ0KNYSr4
I have tried a few different things already and I determined that it has to do something with the physics engine because it only happens when the player isn't kinematic. So, I tried to increase the solver iterations for physics in the project settings, but the bug was still happening. I looked for answers on the internet, yet the only thing I found was to remove Time.deltaTime, though it still doesn't work. I have found that it seems to happen less though when the player is moving fast.
I would really appreciate if somebody could help me with this. This is my first real game and I'm creating it for the Seajam that's happening on itch.io.
Here is the code for my playercontroller script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float playerSpeed = 3f;
private Rigidbody playerRb;
public GameObject cameraRotation;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
}
float verticalSpeed;
float horizontalSpeed;
bool isOnGround = true;
// Update is called once per frame
void Update()
{
//get controlled forward and backward motion
verticalSpeed = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * playerSpeed * verticalSpeed * Time.deltaTime);
//get controlled sidewards motion
horizontalSpeed = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * playerSpeed * horizontalSpeed * Time.deltaTime);
//lock the rotation of the player on the z and x axis
transform.eulerAngles = new Vector3(0, cameraRotation.transform.eulerAngles.y, 0);
//when pressing space jump and prevent air jump
if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
{
playerRb.AddForce(Vector3.up * 10, ForceMode.Impulse);
isOnGround = false;
}
}
//check if the player is on the ground
private void OnCollisionEnter(Collision collision)
{
isOnGround = true;
}
}
Try not locking the player's rotation by script, maybe it is causing the problem due to gimbal lock. Instead go to your player's RigidBody->Constraints and then lock it.
You can read more about it here https://fr.wikipedia.org/wiki/Blocage_de_cardan
I'm having trouble finding my mistake regarding my automatic movement script. I will explain first what i tried to do so you can understand it better. So i am programming in c# in unity. It is for VR. I created a button, that works as a trigger when you are looking at it. When looking at the button a door goes down and the player should move inside a castle (automatically).
The door script works fine but the player is not moving at all. I used a public Vector3 where I declared the position inside the castle where the player should move to (it is only a forward direction).
Unfortunately the code looks fine to me and i cant figure it out why my player wont move :/.
So I tried playing around with the Vectors but i had no luck.
{
public float speed = 0.5f;
public Vector3 castlePosition;
private Vector3 targetPosition;
// Start is called before the first frame update
void Start()
{
targetPosition = transform.position;
}
// Update is called once per frame
void Update()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
if(hit.transform.GetComponent<DoorButton>() != null)
{
hit.transform.GetComponent<DoorButton>().OnLook();
MoveToCastle ();
}
}
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * speed);
}
private void MoveToCastle()
{
targetPosition = castlePosition;
}
}
I was expecting that the MoveToCastle function would put my player inside the castle (at the position that I declared earlier).
Once again the OnLook function from my door is working.
Thank you in advance for your help. :)
Your MoveToCastle stops working as soon as raycast becomes false. You probably should set off some continuous process of moving to target when the raycast hits. For example start coroutine something like this:
IEnumerable MoveToCastle()
{
targetPosition = castlePosition;
while (transform.position != castlePosition) // careful here! see below
{
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * speed);
yield return null;
}
}
Better to compare target and transform coordinates by subtracting and comparing to some small value, otherwise it can go there quite long.
I'm new to Unity, so probably this is a dumb question but I have several days trying to figure it out. I have an enemy walking from one side of a platform to the other. I'm using Raycasting to check if there´s no ground below and turn to the other way.
What I want is for the enemy to walk AROUND the platform (Just like the enemies in Metroid). I set the gravity of the enemy to 0 so it will not fall down, but I don´t know how to make it rotate and keep walking around the platform. I know it could be done with raycasting but I have not clue how to do it.
I will enormously appreciated if anyone can help me with the piece of code I'm missing. Thanks in advance!
public class BlobController : MonoBehaviour {
private Rigidbody2D myRigidBody;
public float moveSpeed;
public LayerMask groundMask;
float myWidth;
// Use this for initialization
void Start ()
{
myRigidBody = GetComponent<Rigidbody2D>();
myWidth = GetComponent<SpriteRenderer> ().bounds.extents.x;
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate()
{
//Check to see if there's ground in front before moving forward
Vector2 lineCasPos = transform.position - transform.right * myWidth;
Debug.DrawRay (lineCasPos, Vector2.down,Color.red);
bool isGrounded = Physics2D.Raycast (lineCasPos, Vector2.down, 2, groundMask);
//If there's no ground, turn around
if (!isGrounded)
{
Vector3 currRot = transform.eulerAngles;
currRot.y += 180;
transform.eulerAngles = currRot;
}
//Always move forward
Vector2 myVel = myRigidBody.velocity;
myVel.x = -transform.right.x * moveSpeed;
myRigidBody.velocity = myVel;
}
}
My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMoving1 : MonoBehaviour {
public float moveSpeed;
private Rigidbody myRigidbody;
private Vector3 moveInput;
private Vector3 moveVelocity;
private Camera mainCamera;
public GunController theGun;
void Start () {
myRigidbody = GetComponent <Rigidbody>();
mainCamera = FindObjectOfType<Camera>();
}
// Update is called once per frame
void Update () {
moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * moveSpeed;
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if(groundPlane.Raycast(cameraRay,out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
}
if (Input.GetMouseButtonDown(0))
theGun.isFiring = true;
if (Input.GetMouseButtonUp(0))
theGun.isFiring = false;
}
void FixedUpdate(){
myRigidbody.velocity = moveVelocity;
}
}
With isKinematic == true You can't change object position through rigidbody, You can only change transform.position.
I think it could be better, if You set isKinematic to false and add stopping distance to enemies, so they can't get too close to player.
Being that your player can no longer be effected by the physics engine, you'd have to manipulate the object's transform manually. Your script isn't ideally setup for it currently, but if I was to hack it into it and try to make it work it would look something like this:
(you can change it from fixedUpdate to update if you're no longer utilizing the physics engine)
void update(){
float x = Input.GetAxisRaw("Horizontal")* Time.Deltatime;
float z = Input.GetAxisRaw("Vertical") * Time.Deltatime;
transform.position = new Vector3(transform.position.x+x,0,transform.position.z+z);
Another way of doing this is to lock the position of Y for the player (assuming Y is the positive "up" direction). isKinimatic is best when you want to move the player or objects around yourself.
I would say upping the mass is better in this case, and you can keep isKinematic unchecked in this case then too. Also apply the lock for Y movement (again if it is the "up" direction from the plane)
Let me know what your solution is regardless, I've had some issues in the past as well with these types of events happening
This is my click to move code, This is my first question, so I'm new to this. If you need any more information I will be happy to give it to you!
I have made a top-down dungeon game (Like Diablo), I completed creating all of the dungeon levels and started to animate and move my player, I got it working starting on the third and last level and it works perfect, I was happy as this is my first time making a game. I created a prefab of the character and moved it into the other levels and only got error when I clicked to move, I have tried to add them in separately but still didn't work sadly.
using UnityEngine;
using System.Collections;
public class ClickToMove : MonoBehaviour
{
public float speed;
public CharacterController controller;
private Vector3 position;
public AnimationClip idle;
public AnimationClip run;
public static Vector3 cursorPosition;
// Use this for initialization
void Start ()
{
position = transform.position;
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButton(0))
{
//Locate where the player clicked on the terrain
locatePosition();
}
//Move the player to the position
moveToPosition();
}
void locatePosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000))
{
if(hit.collider.tag!="Player"&&hit.collider.tag!="Enemy")
{
position = hit.point;
}
}
}
void locateCursor()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000))
{
cursorPosition = hit.point;
}
}
void moveToPosition()
{
//Game Object is moving
if(Vector3.Distance(transform.position, position)>1)
{
Quaternion newRotation = Quaternion.LookRotation(position- transform.position, Vector3.forward);
newRotation.x = 0f;
newRotation.z = 0f;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 10);
controller.SimpleMove(transform.forward * speed);
GetComponent<Animation>().CrossFade("run");
}
//Game Object is not moving
else
{
GetComponent<Animation>().CrossFade("idle");
}
}
}
As Catwood said, double clicking on the error in the console will take you to the relevant line of code that's causing the exception. I'd expect it to be one of the GetComponent calls though as you're trying to call the CrossFade function on something that might return null (in the case that the Animator component can't be found).
As a side note, you should avoid using GetComponent like this as it's inefficient. Instead, create a private / protected variable and store the reference when you first get the component.