this is my first question on StackOverflow, please pardon and fix me if I ask something inappropriate.
I was creating a basic animated scene, where my GameObjects (Which are a couple of pre-animated animals) are running throughout the scene.
Here is the script:
using UnityEngine;
using System.Collections;
public class Locomotion : MonoBehaviour
{
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime);
}
}
Now my question is, how can I make them turn 180 degrees around when they hit a collider? Any modification to my existing code is welcomed
I mostly agree with the fine gentleman in that you should use a Rigidbody component to move your animals.
Something like this:
using UnityEngine;
using System.Collections;
public class Locomotion : MonoBehaviour
{
public RigidBody rb;
void FixedUpdate()
{
rb.velocity=Vector3.forward;
//or you could use rb.AddForce(Vector3.forward)
//but in simple cases such as this one it's not necessary
}
}
Be sure to call all physics calculations from FixedUpdate and not Update, because it you don't your objects can "jitter" in the scene (not going into detail on that).
About the collision detection and the 180:
To detect collisions you have to have a RigidBody component on your objects, as well as a Collider on your objects, as well as on the walls you want to collide with.
The way you check for collisions:
using UnityEngine;
public class Test : MonoBehaviour
{
public Rigidbody rb;
void FixedUpdate()
{
//this is the part that moves your animals,
//i use transform.forward instead of Vector3.forward because this way
//it will point in the forward direction of the animal, even if i rotate it
rb.velocity = transform.forward;
}
private void OnCollisionEnter(Collision collision)
{
//i tagged the walls i want to turn back the animals as "wall" in the unity editor
//and here i check if the thing i collided with is a wall
if (collision.gameObject.CompareTag("wall"))
{
//this line basicly says: look in the direction that is currently behind you
transform.rotation = Quaternion.LookRotation(transform.forward * -1);
}
}
}
Related
so I have rigid body and when it collides with another body with low speeds it is working just fine but when it collides with hight speed it goes through the object I've Been have this problem for day and I can't fix it
here's my code
this is my player movement file
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharcterController : MonoBehaviour
{
// Start is called before the first frame update
public Vector3 PlayerMovementVar;
public Rigidbody Rigidbody_comp;
// Start is called before the first frame update
void Start()
{
Rigidbody_comp = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
PlayerMovement();
}
void PlayerMovement()
{
float horizontalAxis = Input.GetAxis("Horizontal")/30;
float verticalAxis = Input.GetAxis("Vertical")/30;
PlayerMovementVar = new Vector3(horizontalAxis,0f,verticalAxis);
transform.Translate(PlayerMovementVar,Space.Self);
}
}
I shouldn't be the one answering this since I have very little knowledge of unity but I'm pretty sure it might be because you are using transform.Translate which I think it avoids collisions try using a character controller instead :)
If you want to use properly Unity physics system you must use Forces instead of Translate direcly your gameobject.
Try this:
Rigidbody_comp.AddForce(PlayerMovementVar);
instead of
transform.Translate(PlayerMovementVar,Space.Self);
RigidBody movement and Transform movement are different from each other, each causes a different type of movement. when moving with a rigidbody, in order to use its physics ability, you should move it instead of the usual transform.Translate.
Rigidbody_comp.AddForce(PlayerMovementVar);
i want to make the characters in my game collide with objects around them and stop moving. the thing is the characters just spawn and keep walking down the map until they're out of the Canvas view.
my characters have Constantmove script that i assigned to them which is this one:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterConstantMove : MonoBehaviour
{
GameManager Game_Manager;
void Start()
{
GameObject gameController = GameObject.FindGameObjectWithTag("GameController");
Game_Manager = gameController.GetComponent<GameManager>();
}
void Update()
{
transform.Translate(Game_Manager.moveVector * Game_Manager.moveSpeed * Time.deltaTime);
}
}
What do i do to make them stop around the desk and just stay idle when they collide there?
You are moving them with transform.Translate() function, which does not include physics. If you want them to collide, you would have to add Rigidbody2D component and move them using velocity property: https://docs.unity3d.com/ScriptReference/Rigidbody2D.html
I am currently working on the Flooded Grounds Unity Asset, I'm implementing an Alien NPC, with a script that tells it to follow the player.
The problem that I'm encountering is that the Alien turns his back to the player and I can't figure out why. I also tried rotating it by 180° on the Y axis (both in the transform and inside of the script using transform.rotate.y - when using the transform doesn't make any difference while using it in the update function just makes it constantly snap back and forth).
Here's a video of the issue:
https://drive.google.com/file/d/1tC9zJWKXXDuNZNZJbl2htBUgTPSTB4IG/view?usp=sharing
And here's the script that I'm using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyFollow : MonoBehaviour
{
public NavMeshAgent enemy;
public Transform Player;
private Rigidbody alienRb;
private Animator alienAnim;
// Start is called before the first frame update
void Start()
{
alienRb = GetComponent<Rigidbody>();
alienAnim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
enemy.SetDestination(Player.position);
if(enemy.velocity.magnitude > 0)
{
alienAnim.SetTrigger("Walk");
}
}
}
Any help would be very appreciated!
Hello Mazza ^^ First of all, I have to say that your alien monster is really cute :D Anyway, did you try transform.LookAt(Player.transform.position)? Also, transform.rotation is might not be affective, maybe you can try alien.transform.Rotate(0.0f, 90.0f, 0.0f, Space.Self); or transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y - 180f, transform.rotation.z)
I'm new, and I've got hard time to respawn my AI (right now he just a cube that follow my player) after he been destroy. I believe its because the script sits on the object that get destroyed. but what I need to do to respawn it?
(although I'm sure my respawn code is not good :\ (It's mobile-android project) )
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTesting : MonoBehaviour
{
[SerializeField]
public GameObject player;
public GameObject enemy;
private Rigidbody body;
Vector3 accelerationDir;
// Use this for initialization
void Start()
{
body = GetComponent<Rigidbody>();
}
private void Update()
{
accelerationDir = Input.acceleration;
if (accelerationDir.sqrMagnitude>=5)
{
EnemyDead();
}
}
void EnemyDead()
{
Destroy(enemy);
Invoke("Respawn", 5);
}
void Respawn()
{
enemy = (GameObject)Instantiate(enemy);
enemy.transform.position = transform.position;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 toTarget = player.transform.position - transform.position;
float speed = 1.5f;
transform.Translate(toTarget * speed * Time.deltaTime);
}
}
Thanks very much!
I am supposing that your enemy GameObject is inside the scene holding your EnemyTesting MonoBehaviour instance (correct me if I'm wrong).
If this is the case, you cannot instantiate a gameObject that is destroyed.
As #derHugo pointed out, you should not use Destroy and Instantiate for your use case. It would be better to set inactive the enemy GameObject, move it to the position that you want, an (re)set it active. It will look like the enemy respawned.
If you want to dig the subject later, look at the object pooling game optimization pattern.
Otherwise, if you still want to use Instantiate for respawning, I would create a prefab of your enemy GameObject. The enemy GameObject referenced in the EnemyTesting field (in the Inspector view), would be your prefab from the project hierarchy instead of a GameObject inside the scene.
This way, you would be able to instantiate an enemy GameObject as many times as you want (and use it in other scenes!). Don't forget to hold a reference to the instantiated enemy GameObject so you can know which one you want to destroy. It would looke like this :
enemy = Instantiate(enemyPrefab, transform.position, transform.rotation);
You can replace transform with the transform of your choice, for example the transform of an empty enemyRespawnPoint GameObject in your Scene.
Do you see any error in the console ?
I have a rectangle player sprite with a Box Collider 2D and a Rigidbody2D attached. I also have a script for point-and-click movement attached to the player object (i.e. player moves to mouse click position). However as soon as the player character hits a collider, it starts to jitter rather than just fully stop. I don't know a lot about Unity physics other than what I've picked up in a few tutorials, so I'll include as much relevant information as I can.
The Rigidbody 2D component has all forces set to 0, except for mass being 0.0001. The body type is dynamic, and collision detection is set to continuous. My movement script looks like this, got it straight from a tutorial:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
public float speed = 1;
private Vector3 target;
void Start()
{
target = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0)) {
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
Is there an easier way to implement smooth point-and-click movement?