How to move enemy characters? - c#

I have random enemy characters spawned into a map using Unity 3D. The enemies have rigid bodies with gravity enabled. I use MovePosition to move them around the map (in the 'forward' direction) in the Update() method and select a random rotation so they 'wander' around randomly.
Because gravity is enabled when they walk up or down hills on the island, it all works correctly (they stick to the terrain).
The problem arises when I fire an arrow at them. Sometimes they start floating upwards into the sky, despite gravity being turned on.
I tried using AddForce() instead, after reading that may be more appropriate for non-kinematic rigidbodies, but movement became very erratic and so went back to movePosition.
Any ideas how I can stop them floating upwards when hit by arrows sometimes? I'm guessing having enemies walk around randomly and then be able to be hit by arrows must be a fairly common requirement for game designers, but not been able to find a best practice method to use anywhere on google?
void Update() {
...
rigidBody.MovePosition(rigidBody.position + movementDirection * 0.4f * Time.deltaTime);
...
}

It turned out it was due to internal inertia on the enemy objects - just found this video during lunch. Another unityism... so frustrating, but hopefully this answer helps out others in the future:
https://www.youtube.com/watch?v=maIAiSRBEdE
It turned out Fixed constraints were being ignored by unity because of the internal inertia being set on the objects rigid body.

Related

How can i make a rigidbody speed up everytime it collides with a wall at an angle?

I am trying to make a game where i got a ball with an arrow rotating around it. The ball starts as immovable, but when i hit a button i launch it to the direction the arrow is pointing at. Player will have the option mid air to press another button to make the ball "sticky" so when it hits a wall it will stick to the surface and repeat the process till he gets to the top of the level.
Aside from that, i want to give the option to the player to not stick to the wall if he doesn't press that button and instead bounce off the wall but when he does that, the player should speed up with every bounce, giving the option to either play it safe and slow or try to go fast getting more points as he does.
For the early prototyping i used force to move the player up every time he launches but i am not sure how i can make him speed up every time he bounces off the wall. It feels to me like a math problem more than it is a coding challenge. What i am thinking is that i have to find the angle on which player hits the wall, and add force according to that towards the direction he is supposed to follow after the collision.
Sadly i am not that good with trigonometry (working on it though). I am thinking that i might need to use a formula containing sin, cos, tan formulas but i m not sure how to do it. Any help is much appriciated! If you need more information on it please tell me and i ll be happy to provide.
Edit: After the first reply to this question i also found out those links that dive deeper into the subject. I m gona link them here for people that have the same issue.
Bouncing a ball off a wall with arbitrary angle?
http://www.3dkingdoms.com/weekly/weekly.php?a=2
If your ball has velocity vector V=(vx,vy), then after bouncing from standing surface with normal N, ball's new velocity is
V' = V - 2 * N * (V.dot.N)
where dot is scalar product of vectors (vx*nx+vy*ny)
Particular cases:
bouncing from vertical wall (N=(+-1, 0)) causes reversing of vx-component, vy component remains the same. V' = (-vx, vy)
bouncing from horizontal wall (N=(0, +-1)) causes reversing of vy-component, vx component remains the same. V' = (vx, -vy)
Note I recommend to work in velocity vector components, and use angles only when they are really needed.
If you need to calculate bouncing from moving bat, it is worth to change stationary coordinate system to moving one, connected with the bat, find reflection in that system, and revert to stationary system.
Ok so problem was solved!
I want to thank both #MBo and #shingo for their contribution to the solution. While the answer of Mbo solved the problem via trigonometry and gave me nice material to study and figure out how things work, i followed shingo's advice in the comments of my question and managed to do it without diving deep into math.
So basically what he said, and what i did, was to use Unity's physics engine and let the ball hit the wall. After the ball bounces off the wall, it gets a new Velocity vector towards the direction it would go based on physics. I then created an OnColllisionExit check, and when the ball stops colliding with the wall, i AddForce to it to the direction of its new Velocity Vector3.
Works like a charm!
Thank you all for your contributions!

Unity OnTriggerEnter is not being called

I have a flying Dagger with a trigger surrounding it so when it hits an enemy or wall it returns. However sometimes the Dagger just flies straight through. I suspect that happens because its velocity is too high(200), is there a way to fix that?
This is, almost for sure, caused by the high velocity, and in fact this problem is known as "bullet through paper". There are some tricks to address this issue.
As a start, if you are using a Rigidbody, you can go for the dynamic collision detection: this reduces the performances, but it helps a lot for this problem.
You can use Raycasting rather than Collisions, in order to check for the bullet impact.
A trivial advice: in case of the walls, you could just extend the collider in the direction for which the scene does not take place anymore: this way, you would have "wider" walls, but outside of the game field.

How do I fix the floating glitch that is happening to my Player Ball?

I am using Unity3D to make a replica of the game "Rolling Sky" which you can find on the Google/Apple app store. I was able to make a simple floor which the ball will move on and I was also able to make the ball (Player) move left and right. After moving the ball a couple of times back and fourth, it starts float in the air and eventually what it seems like is change it's axis.
I came up with a couple of alternatives that I think would work, but I had trouble coming up with the code to make it function properly.
1) Do not rotate the ball at all. Just have it smoothly move back and forth.
^^ Probably the best solution I could come up with.
or
2) Use CharacterController to have complete control of how the ball reacts to different events, scenarios, etc.
^^ This would probably be the most necessary and hardest of I had to guess.
or
3) Move the ball an x amount of pixels everytime I move left or right.
^^ I would assume this would create a lot more glitches than what I have right now.
public class PlayerController : MonoBehaviour
{
public float speed;
void Update()
{
transform.Translate(Vector3.right * speed * Input.GetAxis("Horizontal") * Time.deltaTime);
}
}
EDIT:
I was able to provide my own answer, but if anyone has any alternatives, feel free to post your solution!
To prevent the player ball from floating into the sky, no other code was needed. Simply go to the Rigidbody component on the Player and expand the "Constraints" menu. Next, check the axis boxes that you would like to freeze the rotation on to prevent the ball from spinning like so in the picture.
Click the link to see the picture
here.
In this case, I did not freeze the ball on the x axis because I eventually want to animate it to spin as if it is rolling forward.
You're using transform.Translate
and
You're using Vector3.right
transform.Translate will directly move the ball without thought of rotation. You will need to take the object's rotation into consideration when translating. You can also use the physics engine and use Rigidbody.MovePosition to force position or Rigidbody.AddForce to utilize physics interactions.
Vector3.right will use the constant value equivalent to Vector3(1, 0, 0). This will not be in regard to the object's rotation or facing.
I suggest looking through Unity's tutorial for a ball-roller and see how they complete the task of user input with a user controlled ball.

How do you reduce the drag experienced when jumping in unity?

I've created a player character in Unity and jumping works like it should.
But when she starts to fall back down to the ground, I want her to fall quickly.
She is almost floating back down, which interrupts the level's feel.
What parameter am I missing that allows her to fall back to the ground?
I'm going for a Mario feel, where he crests at the jump and then falls fairly quickly back down to the ground.
Simply add more gravity to whatever component that controls your characters' physics e.g. If you are using a rigidbody component then increase the gravity property.

How to Prevent RigidBody from passing through other colliders

I've got a coin RigidBody and walls around it with box colliders. For trial purpose I've applied the following code to the coin.
private void OnMouseDown()
{
rigidbody.AddForce(30.0f, 0f, 5.0f, ForceMode.Impulse);
}
But, sometimes the coin passes through the walls, but when I increase the speed from 30 to 50 points it passes through the walls on the first click. I've googled a lot and still got nothing except for the DontGoThroughThings Script which doesn't work for me or I don't really know how to use it.
I've always added a continuous dynamic on the coin and continuous collision detection on the walls but still doesn't work.
the problem with physics collision detection is that sometimes when the speed of an object is too high (in this case as a result of a force added to the rigid body) the collision wont be detected. The reason is that the code you are executing is running at x ammount of steps per seconds so sometimes the rigidbody will go through the collider between one step to another. Lets say you have a ball at 100 miles per hour and a wall that is 1 feet wide, the code will move the ball a determined ammount of feets everytime the code is runned according the physics of it, so the movement of the ball is virtualized but its not a real physical movement so it can happen that from one step to another the ball can move from point a to b and the wall is between those points and as a result the collision will not be detected.
Possible Solutions.
You have a simple solution that wont be as accurate as it should be and a harder one that will be perfectly accurate.
The solution number one will be increasing the colliders size, according to the max speed your coin can get, that way the collider will be big enough so that the collision wont be missed between one frame to another.
The second and harder solution will be adding an auxiliar to your collision detection, some kind of a security check. For example using physical raycast. You can set a raycast to forward direction and determine if that object is an inminent collision, if it does and once the object isnt being collided by the raycast anymore then your collision detection had failed that way you have your auxiliar to confirm that and call the collision state.
I hope it helped and sorry about my english. If you didnt understound it very much i could help you with code but i will need some code from your project.
See if the colliders have their 'Is Trigger' unchecked.
Also, check if the gameObjects have colliders.
I have faced this problem many times..
Make sure Your coin's Rigidbody has "Is Kinamatic" False, Is Triggger:false,
And also "Is Trigger" of walls is False.
You could save the velocity and position on each update and then test for out of bounds, if the coin leaves the valid area you can restore it at the last valid position or plot the collision yourself if you want to

Categories

Resources