How to make enemy circle player when in range? - c#

I am working on a propably simple script. As I am new to coding and stuff, there is a high chance that my code looks horrible.
Okay, so here's the thing:
I have an enemy triggered, and only spawning when the player get's near a certain point. Then the Enemy has to follow the player, doesn't matter where he is, and keeping a certain range of 3 units.
To this point. Everything works fine.
Now, what doesn't seem to work is, that I need my enemy to "orbit" around my player, when he is in a certain range (3) and only then.
For now, it's orbiting right from the start...what did I miss??
Thats my code so far:
public Transform mTarget;
float mSpeed = 10.0f;
const float EPSILON = 3.0f;
public float speed;
void Start()
{
OrbitAround ();
}
void Update() {
transform.LookAt (mTarget.position);
if ((transform.position - mTarget.position).magnitude > EPSILON)
transform.Translate (0.0f, 0.0f, mSpeed * Time.deltaTime);
}
void OrbitAround() {
if(Vector3.Distance(transform.position, mTarget.transform.position) < 3) {
transform.RotateAround (mTarget.transform.position, Vector3.up, speed * Time.deltaTime);
}
}
Big Thanks in advance, if anyone can help me out.
Cheers,

As #Zibelas said, the Start function is only once.
The Unity documentation states:
Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
So try putting the call to OrbitAround() in the Update function and it should work

Well, didn't really fixed this problem exactly, but I found a way to work around it.
I just enabled the script to orbit around the target, when the enemy get close to it and disabled it, when the player goes away again.
void Update (){
if (Vector3.Distance (transform.position, mTarget.transform.position) < 15) {
script.enabled = true;
}
if(Vector2.Distance(transform.position, mTarget.transform.position) >15) {
script.enabled = false;
}
Still, thanks for the comments and information, guys.

Related

How to convert my Character Controller into Rigibody Movement in Unity?

I'm making a 3D Side-Scroll Platformer Game,
I have trouble with my character when it steps on the moving platform it will not come along on the platform. I want my character to stay on the moving platform so I think converting my Character Controller into Rigibody will help me,
I need help to give me ideas on how I can reuse my Character Controller Script in Rigibody. This is my code, how can I reuse this in Rigibody script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public CharacterController controller;
private Vector3 direction;
public float speed = 8;
public float jumpForce = 30;
public float gravity = -20;
public Transform groundCheck;
public LayerMask groundLayer;
public bool ableToMakeADoubleJump = true;
public Animator animator;
public Transform model;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (PlayerManager.gameOver)
{
//play death animation
animator.SetTrigger("die");
//disable the script
this.enabled = false;
}
float hInput = Input.GetAxis("Horizontal");
direction.x = hInput * speed;
animator.SetFloat("speed", Mathf.Abs(hInput));
bool isGrounded = Physics.CheckSphere(groundCheck.position, 0.15f, groundLayer);
animator.SetBool("isGrounded", isGrounded);
if (isGrounded)
{
//Jump Codes
ableToMakeADoubleJump = true;
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
else
{
direction.y += gravity * Time.deltaTime;
if (ableToMakeADoubleJump & Input.GetButtonDown("Jump"))
{
DoubleJump();
}
}
if (hInput != 0)
{
Quaternion newRoattion = Quaternion.LookRotation(new Vector3(hInput, 0, 0));
model.rotation = newRoattion;
}
//Move the player using the character controller
controller.Move(direction * Time.deltaTime);
}
private void DoubleJump()
{
//Double Jump Codes
animator.SetTrigger("doubleJump");
direction.y = jumpForce;
ableToMakeADoubleJump = false;
}
private void Jump()
{
direction.y = jumpForce;
}
}
I would not recommend switching between the two. It would get tricky, and think about it, you are alternating between two very different things. One is movement and one is physics.
However, I would reccomend adding to your current script so that the player would move with the moving platform.
There is a lot of stuff in this answer, so read the whole thing.
Btw, when I talk about velocity, in your case it is direction.
Since it seems like you know how to code pretty well, I won’t write out the script, rather tell you some physics ideas to get you going in the right direction.
The reason people can stand on a moving platform and not fall off is because of friction.
If you are standing on a gameObject with enough friction (you could add a physics material the gameObject you stand on and change friction there. Note that physics materials only work with rigidbodies, but you might want to use it to just read the value)
First of all, you are going to want to raycast down to obtain the object you are standing on. From there you can get the physics material from hit.collider.sharedMaterial (or any other hit. to obtain data about what object you are standing on.
If they friction is too low, just make the character slip off, like it was before (I assume)
If the friction is above a threshold, get the velocity from the object you are standing on. If it was a rigidbody, hit.rigidbody.velocity. If it is controlled by script, use hit.collider.gameObject.GetComponent<scriptname>().velocityvariablename This part is continued later on
This is not necessary but useful: You can think of this as grabbing on a rope. When you are grabbing on a slippery rope, and someone pulls it (Like tug of war), You won’t move because the rope will slide through your hands. If the rope had grip tape on it and someone pulled it, you would come with it because it has more friction. You can think of the platform the same way. Now on to the more complex part: When you grip a rope that is stationary, and someone pulls it, you come with it as its velocity changes. When the rope is already being pulled, so its velocity is not stationary and it is already something. You grab onto it and a similar thing happens. It is like you are becoming a part of that rope. Similar to how if you are running, the arms and legs and head is a part of you. If you lose grip, you are no longer a part of that body, like your arms falling off when running. In other words, you become part of the body when you attach yourself to it.
Bottom line:
Get the velocity of the platform and set platformVel to it, do not add that to velocity, rather do a seperate controller.Move(platformVel).
A small customization:
Vector3.Lerp the platformVel to 0, so it doesn’t change while on the platform, but gradually goes to (0,0,0) when you get off. This way, there is a little momentum maintained from standing on the platform.
Feel free to ask anything in the comments.

How to make Unity gravity and AddForce accelerate

I'm making a clone of Hollow Knight, and my character is falling at a constant rate instead of accelerating. I tried changing the gravity scale and using Addforce instead of rigidbody gravity.
This is the code I tried for the gravity
public Rigidbody2D rb;
void FixedUpdate(){
rb.AddForce(-transform.up*100f * Time.fixedDeltaTime, ForceMode2D.Impulse);
}
I've done a lot of testing and it doesn't seem like what you say is true.
In a new project, I simply created a rigidbody2D gameobject and added this script to it.
public void Start()
{
StartCoroutine(PrintDistance());
}
IEnumerator PrintDistance()
{
float p = 0;
for (; ; )
{
p = transform.position.y;
yield return new WaitForSeconds(1);
print("Distance per second: " + (transform.position.y - p));
}
}
As you can see from the console, every second, the distance traveled increases, so the speed is not constant but accelerated.
How can you see that the falling speed is not constant?
Try adding this script and tell me the results.
I can speculate that some other part of your project is causing this problem, or you have changed some properties in the Physics panel in Project Settings, but that is not likely.
if you think my answer helped you, you can mark it as accepted. I would very much appreciate it :)

Why is this transform.position reset between frames

So, my issue is as follows:
I'm developing a very simple 2D game as I'm quite new to Unity. Basically, there is a knight, and there is a troll. I'm developing my custom AI for the troll and got stumped at the very beginning. I tried to make the troll sprite correctly rotate and walk towards the player (in Update()), but then it turned out that the troll game object doesn't move as much as a millionth of a unit (although it rotates correctly)!
Now, what is special about my problem is the following: it's not about using localPosition instead of position (the troll has no parents – pun intended), it's not about referencing the transform in the script via "[SerializeField]", it's not about working with static objects or messed-up prefab coordinates or any of the other issues I've found in my desperate 10-hour search on the Internet. No, the issue is that I HAVE the troll transform in my code, I modify it successfully, but then it fails to be applied to the in-game troll object. Let that sink in – I am correctly modifying the correct transform (checked multiple times via debugging) but at the beginning of the next frame, all changes get magically reverted and the transform doesn't move the slightest.
I've made almost twenty modifications to my code in order to try and make it work (including separating stuff in different files as was suggested in a particular forum topic) but it just doesn't, and I can't think of anything else. Any help is very, very much appreciated.
public class EnemyController : MonoBehaviour
{
[SerializeField]
private Animator animator;
[SerialiseField]
private float walkingSpeed;
[SerializeField]
[Header("The aggro range of the enemy in Unity units.")]
private float aggroRange;
private float dir;
private Transform playerTransform;
void Update()
{
if (Aggro(playerTransform, aggroRange))
{
//WALKING:
WalkTowards(playerTransform, walkingSpeed);
}
}
private void WalkTowards(Transform targetTransform, float walkingSpeed)
{
animator.SetBool("IsRunning", false);
dir = 0.0f;
//Get the direction (left or right)
if (targetTransform.position.x < transform.position.x) //Left
{
dir = -1.0f;
//Flip the sprite to the left
transform.rotation = Quaternion.Euler(0.0f, 180.0f, 0.0f);
}
else //Right
{
dir = 1.0f;
//Flip the sprite to the right
transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);
}
transform.position = new Vector3(
transform.position.x + (walkingSpeed * dir * Time.deltaTime),
transform.position.y,
transform.position.z
);
Debug.Log(
string.Format("Troll 1 position:\nx: {0:#.##}", transform.position.x) +
string.Format(" y: {0:#.##}", transform.position.y) +
string.Format(" z: {0:#.##}", transform.position.z)
);
}
}
(NOTE: Aggro() is a custom method that determines when the enemy aggros; not included in the code as it is irrelevant to the issue)
So basically, transform.position gets changed correctly in the script and stays that way until the end of the method, but at the beginning of the next frame – i.e. when WalkTowards() gets called again, the transform.position remains the same as it was at the beginning of the last frame – as if no calculations or changes were ever made.
#Ruzihm,
You were right!!! Turns out the Animator component of the troll was causing the issue – "Apply root motion" was off, I turned it on and the position gets correctly updated now. Thank you ever so much for the help!
Example:

Why does my player not move automatically?

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.

Unity Jump function issue

I've been working on this script for the past day. For some reason my character will not jump as long as it's animator is active. I've got into the animation (there is only one) and removed all references to the animation placing a position anywhere and still the issue presides.
I have discovered that I can make my player jump if I use Co-routine which I'm using. However, I'm still new to using them and I can't work out why my player won't fall to the ground once a force has been added to it. And my player only moves up when the button is clicked. Could someone please take a look at my script and tell me what I'm doing wrong?
public float jumpSpeed = 100.0f;
public float jumpHeight = 2.0f;
public AudioClip jumpSound;
private GameObject pos;
private bool moving;
private bool isJumping;
void Start()
{
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButtonDown(0))// && !moving)
{
isJumping = true;
StartCoroutine(JumpPlayer(gameObject.transform.localPosition));
}
else
{
isJumping = false;
}
}
IEnumerator JumpPlayer(Vector3 startPos)
{
Vector3 jump = new Vector3(transform.localPosition.x, jumpHeight, transform.localPosition.z);
float t = 0f;
t += Time.deltaTime / jumpSpeed;
rigidbody.AddForce(Vector3.up * jumpSpeed);
//gameObject.transform.localPosition = Vector3.Lerp(startPos, jump, 0.5f);
//isJumping = false;
yield return null;
}
Firstly, your use of coroutine isn't doing anything in particular - because it only does yield return null at the end, it'll run in a single frame and then exit. You could make it a regular void function and you shouldn't see any change in behaviour.
Removing other redundant code and you have just this:
if(Input.GetMouseButtonDown(0))
{
rigidbody.AddForce(Vector3.up * jumpSpeed);
}
This force is added for only a single frame: the frame where the mouse button is pressed down (if you used Input.GetMouseButton instead, you'd see the force applied for multiple frames).
You say "my player only moves up when the button is clicked" but I'm not clear why that's a problem - perhaps you mean that the player should continue to move up for as long as the button is held, in which case you should refer to my previous paragraph.
The most obvious reasons for the player not falling again are related to the RigidBody component: do you have weight & drag set to suitable values? An easy way to test this would be to position your player some distance from the ground at the start of the scene, and ensure that they fall to the ground when you start the scene.
Another reason might be that you're using the default override of .AddForce in an Update cycle. The default behaviour of this method applies force during the FixedUpdate calls, and you might find that using ForceMode.Impulse or ForceMode.VelocityChange gives you the result you're looking for.

Categories

Resources