void Update()
{
if (pickUp)
{
if(Roll.hasStopped)
{
animator.SetTrigger("Walk Forward");
Vector3 targetDirection = (target.position - transform.position).normalized;
target.rotation = Quaternion.LookRotation(targetDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, target.rotation, Time.deltaTime);
}
}
}
The transform is the player and he is start walking forward "Walk Forward", but he never rotate towards the target. he keep moving straight walking forward.
The "Walk Forward" is a trigger parameter i'm using in my animator controller on a transition to a state with HumanoidWalk animation.
The question is why the transform is not rotating towards the target and keep walking straight forward instead ?
Maybe you're overriding the rotations with the animator.SetTrigger? Idk too much of animation, but It seems odd to me that animator.SetTrigger is called in every frame and after that there's no flag raised to stop calling it over and over.
From what I've seen in the docs, this trigger gets called after a certain event (i.e press a key) but not in every frame. Hope it helps :)
Related
I have a script that makes the swamp track and follows the player. It workes fine. But when I ad an animation to the enemy (a swamp jumping towards the player) it doesn't move.
I've tried removing the position under animation, but then the swamp does not jump. It just scales. This does though fixe the problem with not following the player. so I think the problem is the animation on the position.
public class EnemyAI : MonoBehaviour
{
public float speed;
private Transform playerPos;
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime);
}
}
Animation is the reason that takes over the position and the script becomes useless. As you have mentioned it jumps (Y-axis) and the position in the animator controller takes over. I would suggest try doing two things:
(a) Add a parent to this swamp gameObject and add animation for jumping to this parent
(b) Add MoveTowards() function to Swamp gameObject.
Through this, the parent gameObject will only perform animation of jumping and the child gameObject will perform MoveTowards() function.
I am working on a 2D Platform game, and i realized that the player's jumping function doesn't work the same way every time, for example. The jumping height is different if the player jumps while moving/running or if the player jumps without moving.
I have 2 separated functions Move() and Jump(), Move() uses transform.Translate to make the player move, and Jump() uses rigidBody.AddForce() to make the player jump. I've already tried to change the player Move() function to use rigidBodies to make the player move instead of using transform.Translate(). And it didn't worked.
I've also tried make the player jump using transform.Translate, which solved the inconsistent jumping height problem, but the player just teleports up instead of jumping
this is a representation of my code structure, not the actual code, because the actual code is like 600 lines
public class Player
{
float JumpSpeed;
bool isGrounded;
void Update()
{
if (Input.GetKey(KeyCode.A))
Move(Directions.Left);
if (Input.GetKey(KeyCode.D))
Move(Directions.Right);
if (Input.GetKeyDown(KeyCode.Space))
Jump(JumpSpeed);
}
public void Move(Directions dir)
{
Vector2 speed;
//figure out speed and etc...
//makes the player move in the right direction and speed
transform.Translate(speed * Time.deltaTime);
}
public void Jump(float speed)
{
if(isGrounded)
rigidBody.AddForce(new Vector2(0, speed * Time.deltaTime), ForceMode2D.Impulse);
}
}
Not sure if this is specifically your issue, but using translate to move the player and then adding force to jump isn't really the best way to approach the problem.
I would look into using the velocity part of the rigidbody for both the jump and the movement. This would prevent any weirdness that Translating the object could cause.
I want a gameobject spinning around its y-axis. This spinner should have a initial movement direction and when colliding with something, it should change its direction.
I created a little picture to show what I mean, but I want the behaviour for a 3D game.
So I just started with the rotation of the spinner,
public class Spinner : MonoBehaviour
{
[SerializeField]
private float movementSpeed; // speed when moving
[SerializeField]
private float rotationSpeed; // speed when rotating
private Rigidbody rigid;
private Vector3 movementDirection; // the direction the spinner is moving
private void Start()
{
rigid = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
transform.Rotate(0, rotationSpeed, 0); // rotate the spinner around its y-axis
}
private void OnCollisionEnter(Collision col)
{
// set new direction
}
}
How can I move the spinner, that it moves along a direction and whenever it collides with something, it changes its direction. It should never stop moving or rotating.
I would like to point out a few things:
The Unity Physics Engine will make collisions to absorb part of the force which moves your spinner, so unless you keep adding "artificial" forces to the spinner it will eventually stop.
The "air friction" in your scene will also reduce the force of your
spinner, so it will slow it down. You should add a material to the
spinner which has 0 Dynamic Friction
Based on the comment you left in #reymoss' answer, you may consider
to add the bouncy material to the walls, and not to the spinning
GameObject.
To sum up, the issue here is if you want a GameObject to bounce against a wall using the Physics Engine, the object will eventually stop, because some of the forces will be absorbed in each collision. That means you will need to keep adding external forces every time a collision takes place, to keep it moving endlessly.
Something you can try is,
1- Add a bouncy material to the walls and remove the dynamic friction of your spinner. In the following link you can learn about this:
https://docs.unity3d.com/Manual/class-PhysicMaterial.html
2- Add to the Spinner a Collider, so when it detects a collision with a wall (you can tag the walls as so for example) add an additional force to the spinner in the direction it is already moving, so it will compensate the energy lost during the collision.
void OnTriggerExit(Collider other) {
if(other.tag == "wall") {
rigidbody.AddForce(rigidbody.velocity.normalized * Time.deltaTime * forceAmount);
}
}
The idea is to let the Engine decide the direction of the Spinner after the collision with the wall, and as soon as the GameObject leaves the trigger, you add an additional force in the current direction.
Then you can play with the Bounciness of the wall's material and with the forceAmount, until your spinner moves as you have in mind.
Note: Since you will have 2 materials, one in the walls and another in the spinner, maybe playing with the Friction Combine and Bounce Combine you will be able to avoid the force lost during collisions, so you will not need to add the external force I mention in the second step. However I have never tried this.
Let me know if it works. I can't try myself the solution until I arrive home.
If you give the object an initial velocity, attach a collider, create and assign a Physics Material 2D to the collider (to apply bounciness), and attach Colliders to the walls, you can have it bounce around with minimal code.
private void Start()
{
rigid = GetComponent<Rigidbody>();
rigid.velocity = new Vector3(2f, 3f, 1f) // initialize velocity here
}
I have a Rigidbody attached to my character controller and my enemies. I want the enemies to be able to surround me and have me trapped without me being able to move, so I set the mass property accordingly.
There's just a small problem - if I don't set my mass high enough, the moment the enemies collide with me, my player will go flying into the air. If I don't set my enemies' mass high enough, I will be able to walk right through them. How can I fix this issue? Here is the movement code for the player:
using UnityEngine;
using System.Collections;
public class CharController : MonoBehaviour {
public float speed;
void Start () {
Cursor.lockState = CursorLockMode.Locked;
}
void Update () {
float translation = Input.GetAxis ("Vertical") * speed;
float strafe = Input.GetAxis ("Horizontal") * speed;
translation *= Time.deltaTime;
strafe *= Time.deltaTime;
transform.Translate (strafe, 0, translation);
if (Input.GetKeyDown ("escape")){
Cursor.lockState = CursorLockMode.None;
}
}
}
The problem here is that you're using Transform.Translate() to move your player object. As a result, the player is being moved into clipping with your enemy objects in between physics calculations - so when the next physics calculation comes around, there will be a massive repulsing force to correct this. This is what's sending your player flying.
A better alternative is to use Rigidbody.AddForce() (or one of its variants) to indirectly move your player object. This allows the player object's movement to be taken into account during physics calculations, so it can collide with and be stopped by enemy objects before it starts clipping into them.
If you retrieve and store a reference to the player's Rigidbody in a variable, then you can replace Translate() with something like:
rigidbody.AddRelativeForce(strafe, 0, translation);
Hope this helps! Let me know if you have any questions.
Make sure IsKinematic is checked. UseGravity can be checked or not depend on your situation.
That way, you rigidbody will not be affected by force, collision or joint and is under full control of your script. But maybe they will lose the ability to detect collision as well but I'm not so sure, I haven't tested it yet.
If that was the case, uncheck the IsKinematic and instead, check FreezeRotation and FreezePosition as well. That way, you revoke control of the physics from affecting your position and rotation. You will manually manipulate position & rotation from your script (using CharacterController).
References:
https://docs.unity3d.com/ScriptReference/Rigidbody-isKinematic.html
https://docs.unity3d.com/Manual/class-Rigidbody.html
I have several formulas I use for firing a bullet at a target, but it all breaks down when the player moves from his original position and the bullet reaches the old position of the player as intended.
When PlayerPosition == BulletPosition, how do I make the bullet keep going in the right direction if it misses? My problem is once the bullet reaches where it was supposed to go it stops and I need a new formula to keep it moving.
If it hits the player, that's easy, remove the item, but I can't seem to find a good solution. Below is some code, it's super simple for now.
var movement = PlayerPosition - Position;
if (movement != Vector2.Zero)
movement.Normalize();
//var angle = Math.Atan2(movement.Y, movement.X);
Position += movement*_projectileMoveSpeed;
Did you intend the bullet's speed to be affected by the distance from the player?
I'd just save the velocity, then use that in the future frames. In pseudocode:
to shoot a bullet:
direction is sign(PlayerPosition - Position)
in each frame:
for each bullet:
modify position by direction * projectileMoveSpeed
handle collision (player or screen edge)