Character is not colliding with other other objects in Unity3D - unity3d

I'm working on a game right now (first 3D styled game), and I have a problem with my character colliding. I have a Player object, which has another object(s) as the real moveable characters (now I have only one). I have rigidbody and box collider too attached to my character. I have made a level (with hand-placed platforms), and I would like avoid my character of falling of the platforms, while the user control it. I have tried to place a cube on the side of the platform(s), with box collider attached to it, but the character not detect the colliding for some reasons. I would like my character to be stopped by the collider "cube", but it doesn't happen.
I use this script to move my object (attached to my character Player object) :
public class Bounce : MonoBehaviour {
float lerpTime;
float currentLerpTime;
float perc = 1;
Vector3 startPos;
Vector3 endPos;
bool firstInput;
public bool justJump;
public GameObject player;
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("up") || Input.GetButtonDown("down") || Input.GetButtonDown("left") || Input.GetButtonDown("right")) {
if (perc == 1) {
lerpTime = 1;
currentLerpTime = 0;
firstInput = true;
justJump = true;
}
}
startPos = gameObject.transform.position;
if (Input.GetButtonDown("up") && gameObject.transform.position == endPos) {
endPos = transform.position + player.transform.rotation * (new Vector3(0, 0, 1f));
}
if (Input.GetButtonDown("down") && gameObject.transform.position == endPos) {
endPos = transform.position + player.transform.rotation * (new Vector3(0, 0, -1f));
}
if (firstInput == true) {
currentLerpTime += Time.deltaTime * 5;
perc = currentLerpTime / lerpTime;
gameObject.transform.position = Vector3.Lerp(startPos, endPos, perc);
if (perc > 0.8f) {
perc = 1;
}
if (Mathf.Round(perc) == 1) {
justJump = false;
}
}
}
void OnCollisionEnter(Collision collision) {
Debug.Log("!!!!!!!");
}
}
And I use this script on the character itself: (to rotate and animate it)
Code (csharp):
public class AnimationController : MonoBehaviour {
Animator anim;
public GameObject thePlayer;
// Use this for initialization
void Start () {
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
Bounce bounceScript = thePlayer.GetComponent<Bounce>();
if (bounceScript.justJump == true) {
anim.SetBool("Jump", true);
}
else {
anim.SetBool("Jump", false);
}
if (Input.GetButtonDown("right")) {
//transform.rotation *= Quaternion.Euler(0,30,0);
transform.RotateAround(transform.position, Vector3.up, 90);
}
if (Input.GetButtonDown("left")) {
transform.Rotate (0, -90, 0, 0);
}
}
}
It's only colliding when the cube not isKinematic, but it doesn't stop my player from getting through the cube for some reason.
I have read some sites about problems like this, but nothing helped yet.
It would be great if you can give me any code improvements :)
EDIT1:
Sorry, for answering so late, I couldn't do anything with my game in the last few days. Today I have tried to do something with raycasts, you can see my code, for my first try just in the update method:
void Update () {
if (Input.GetButtonDown("up") || Input.GetButtonDown("down") || Input.GetButtonDown("left") || Input.GetButtonDown("right")) {
if (perc == 1) {
lerpTime = 1;
currentLerpTime = 0;
firstInput = true;
justJump = true;
}
}
startPos = gameObject.transform.position;
/* if (Input.GetButtonDown("right") && gameObject.transform.position == endPos) {
//endPos = new Vector3(transform.position.x + 0.5f, transform.position.y, transform.position.z);
}
if (Input.GetButtonDown("left") && gameObject.transform.position == endPos) {
endPos = new Vector3(transform.position.x - 0.5f, transform.position.y, transform.position.z);
}*/
Vector3 fwd = player.transform.TransformDirection(Vector3.forward);
RaycastHit objectHit;
if (Physics.Raycast(player.transform.position, fwd, out objectHit, 2)) {
if (objectHit.collider.tag == "Wall") {
Debug.Log("WALL RAYCAST HIT!");
}
}
if (Input.GetButtonDown("up") && gameObject.transform.position == endPos) {
endPos = transform.position + player.transform.rotation * (new Vector3(0, 0, 1f));
}
if (Input.GetButtonDown("down") && gameObject.transform.position == endPos) {
//endPos = transform.position + player.transform.rotation * (new Vector3(0, 0, -1f));
}
if (firstInput == true) {
currentLerpTime += Time.deltaTime * 5;
perc = currentLerpTime / lerpTime;
gameObject.transform.position = Vector3.Lerp(startPos, endPos, perc);
if (perc > 0.8f) {
perc = 1;
}
if (Mathf.Round(perc) == 1) {
justJump = false;
}
}
}
With this I can get the Debug Log WALL RAYCAST HIT 2-3 times at a time, but only once. As I move the character it won't appear again, for some reason (I think it should because the update method is called in every frame).
Although when I place it in the Input.GetButtonDown("up") method, it won't log anything:
if (Input.GetButtonDown("up") && gameObject.transform.position == endPos) {
fwd = player.transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(player.transform.position, fwd, out objectHit, 2)) {
if (objectHit.collider.tag == "Wall") {
Debug.Log("WALL RAYCAST HIT!");
}
}
endPos = transform.position + player.transform.rotation * (new Vector3(0, 0, 1f));
}

When you update the transform.position you actually "teleport" yout object to the new position. Even when you do this smoothly, using something like the Lerp function, as you do on your move script, Unity understands that you are teleporting your object to a new coordinate.
This is not wrong, All games work like that. Functions like Lerp just create the ilusion of movement, so the player fell like the character actually moved from one point to another.
What is happening is that your script keeps telling the character to move to a new position, despite any objects on its path. The collision happens, but your Update function still places the character on ints new position.
I can think of two possible ways for you to solve this:
Create an OnCollisionEnter() function for your Move script that somehow stops your movement. By creating a flag like you did with the firstInput you could achieve this.
Instead of updating your transform.position you could use a rigidbody to handle the movement and collisions for your. This way, everytime you need to move your character you will need to add some velocity to the character rigidbody, instead of directly updating the transform.position.
Since your character doesn't move in a constant way, but in a "one step at a time" way, I think the first solution is a better suitted for you.
The code will be something like this
void OnCollisionenter(Collision collision)
{
collided = true;
}
and the end of your Move script should be updated to
if(!collided)
{
if (firstInput == true) {
currentLerpTime += Time.deltaTime * 5;
perc = currentLerpTime / lerpTime;
transform.position = Vector3.Lerp(startPos, endPos, perc);
if (perc > 0.8f) {
perc = 1;
}
if (Mathf.Round(perc) == 1) {
justJump = false;
}
}
}
else
{
// Remember to reset this when you stop your character
endPos = transform.position;
collided = false;
}
This time I couldn't test the code before writting it here, so you may need to do some changes before it works.
ps: I don't think you need your firstInput variable. Once it is set to true, you never set it to false again. Also, the Input.GetButtonDown() function will only return true on the first frame a button is pressed wich is what I guess you intended when you created firstInput.
ps2: My solution added a collided boolean attribute to your class, so don't forget to add a line private bool collided; with your other class attributes. Also, read that chapter about the state machine pattern I recommended you on your other question. Creating this kind of control attribute suach as the collided boolean is not a good practice and if you had implemented a state machine this could be avoided.

Hey I had a similar problem i was using an animated model from Mixamo.com and I notices that for some strange reason the character didn't collide with boundaries despite having collider, for some reason it didn't work until i added a CharacterController to my model instead of a collider just search for the CharacterController and add it as you would add any script or rigid body to your game object.
Hope it Works XD Greetings

Related

My variable changes after my gameobject moves, when there is no input to change the variable

I'm trying to get the last position of my gameobject, before it stops moving, but the "lastPos" variable keeps being magically changed to the current position, after my gameobject moves. (I'm probs being stupid)
The reason I'm doing this is to try to add smoothing to the end of the movement of my gameobject, instead of stopping suddenly after it being let go, I want it to gradually slide to a stop. So I was thinking if I found the difference between last position before it stops and the current one, I could add some velocity to the end of it, depending on the distance between the two points, the more velocity it would add.
I couldn't find a tutorial on how to add this.
The problem is probably in the last 3 If statements.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
bool dragging = false;
Vector2 offset;
Transform toDrag;
Transform lastPos;
float posDif;
private void Start()
{
Application.targetFrameRate = 60;
}
void Update()
{
Vector2 v2;
if(Input.touchCount != 1)
{
dragging = false;
return;
}
Touch touch = Input.touches[0];
Vector2 pos = touch.position;
if(touch.phase == TouchPhase.Began)
{
toDrag = gameObject.transform;
v2 = new Vector2(pos.x, pos.y);
v2 = Camera.main.ScreenToWorldPoint(v2);
offset.x = toDrag.position.x - v2.x; offset.y = toDrag.position.y - v2.y;
dragging = true;
Debug.Log("TOUCH");
}
if (dragging && touch.phase == TouchPhase.Moved)
{
if (touch.phase != TouchPhase.Stationary && touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
{
lastPos = gameObject.transform;
}
v2 = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
v2 = Camera.main.ScreenToWorldPoint(v2);
toDrag.position = v2 + offset;
gameObject.transform.position = new Vector2(v2.x + offset.x, -2.67f);
Debug.Log("Last Pos: " + lastPos.position.x);
}
if (dragging && (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled))
{
dragging = false;
posDif = gameObject.transform.position.x - lastPos.position.x;
gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(posDif * 10f, 0f);
Debug.Log("Current Pos: " + gameObject.transform.position.x);
Debug.Log(posDif);
}
}
}
Your lastPos is set to your current gameObject transform. It’s a class, so a reference object, so you’ll always have the latest values.
If you change the type of the lastPos variable to be a Vector3 you’ll be storing that value, at the time you record it. transform.position is a Vector3 which is a struct (a value type).
...
private Vector3 lastPos;
...
if (dragging && touch.phase == TouchPhase.Moved)
{
lastPos = gameObject.transform.position;
v2 = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
v2 = Camera.main.ScreenToWorldPoint(v2);
toDrag.position = v2 + offset;
gameObject.transform.position = new Vector2(v2.x + offset.x, -2.67f);
Debug.Log("Last Pos: " + lastPos);
}
If what I’m talking about sounds alien, here’s the official docs at Microsoft describing the difference between structs (value types) and classes (reference types). Choosing Between Class and Struct

Unity Mobile - How to make fluid swipe to move movement?

So I am working on a personal project, and I had this idea for a movement that I don't know to realize. So the project(game) is for phone, and what I want to, is to when I swap in a direction, that vector becomes its closest axis (ex: 70 degrees will be (0,1) while 35 will be (1,0)). So when I get a swipe, I want my character to move in that direction. MAIN ISSUE is I don't know how to make him dash to that location. I know how to make him TELEPORT, but not how to make him DASH. I tried going for Vector2.Lerp, but it is a bit buggy and feels like character does not react on time. Here is the script:
private void Update()
{
if (gameObject.GetComponent<OnDeath>().isDead == false)
{
if (trigger)
{
fractionOfWayThere += 0.1f;
transform.position=Vector2.Lerp(transform.position, finish, fractionOfWayThere);
isMoving = true;
}
if ((Vector2)transform.position == finish)
{
isMoving = false;
animator.SetBool("isMoving", false);
}
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
startPos = cam.ScreenToWorldPoint(touch.position);
}
if (touch.phase == TouchPhase.Ended)
{
endPos = cam.ScreenToWorldPoint(touch.position);
destination = endPos - startPos;
if (Mathf.Abs(destination.x) > Mathf.Abs(destination.y))
{
destination = new Vector2(Funkcija(destination.x), 0);
}
if (Mathf.Abs(destination.x) < Mathf.Abs(destination.y))
{
destination = new Vector2(0, Funkcija(destination.y));
}
if (Mathf.Abs(destination.x) == Mathf.Abs(destination.y))
{
destination = new Vector2(Funkcija(destination.x), 0);
}
finish = (Vector2)transform.position + destination.normalized;
if (Physics2D.OverlapCircle(finish, 0.1f, spike) != null)
{
if (finish.x < transform.position.x)
{
sr.flipX = true;
}
else if (finish.x > transform.position.x)
sr.flipX = false;
trigger = true;
fractionOfWayThere = 0;
isMoving = true;
animator.SetBool("isMoving", true);
}
else
{
finish = transform.position;
}
}
}
}
}
Most of the code is getting the swipe into its axis and flipping sprite, only thing regarding the movement is this:
if (trigger)
{
fractionOfWayThere += 0.1f;
transform.position=Vector2.Lerp(transform.position, finish, fractionOfWayThere);
isMoving = true;
}
Playtesting, this feels realy weird. I tried Vector2.MovePosition(), rb.AddForce() and rb.MovePosition. Any other way to do this, or even using those functionts I have not thought of? All feedback would be highly appreciated!
Lerp is a good Start, but it's linear. A Dash would typically start instantly and slow down over time.
to achieve framerate independent movement, you should use Time.deltaTime in Update. It's neglectable in FixedUpdate as these occur at (almost) fixed timesteps.
You can achieve that by adding an AnimationCurve to your code:
[...]
public AnimationCurve dashCurve = new AnimationCurve.Linear(0,0,1,1); // modify this in inspector!
[...]
if (trigger)
{
fractionOfWayThere += 0.5f * Time.deltaTime; // fractionOfWayThere takes 0.5 second to grow from 0 to 1.
transform.position = Vector2.Lerp(transform.position, finish, dashCurve.Evaluate(fractionOfWayThere));
isMoving = true;
}
Set up the AnimationCurve like this:

Unity3D bird flying back and forth

I'm trying to create a bird moving across screen along x axis.
bird.transform.position = Vector3.Lerp (pos1, pos2, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f);
Using this in Update() the bird flies only once. I want that after it flies to the right, it should wait 2-3 seconds and then fly back with a different sprite.
transform.translate doesn't work like this. Any help will be appreciated.
you would need to put in another LERP for going the other direction and have a variable for which way the bird is flying so roughly:
bool goleft;
if(goleft)
{
if(transform.position != pos2)
{
transform.position = Vector3.Lerp (pos1, pos2, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f);
}
else
{
goleft = false;
//change the direction the bird is facing here
}
}
else
{
if(transform.position != pos1)
{
transform.position = Vector3.Lerp (pos2, pos1, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f);
}
else
{
goleft = true;
//change the direction the bird is facing here
}
}
Hope that helps
Not tested but i would start here:
Vector3[] posts;
int current = 0;
float speed = 5.0f;
float threshold = Single.Epsilon;
float delay = 2.0f;
public void Update() {
if(!waiting && posts.Length > 0)
{
if(!Mathf.Approximately((posts[current].position - transform.position).sqrMagnitude, threshold)
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, posts[current].position, step);
}
else StartCoroutine("Next");
}
}
IEnumerator Next() {
waiting = true;
yield return new WaitForSeconds(delay);
current = (current + 1) % posts.Length;
waiting = false;
}
This will also allow you to have as many posts as you want to have, and all your movement dynamics can be handled in Next(), whereas, if you want him to go from post 0...1...2...3...0...1.. or 0...1...2...3...2...1...
If you want the latter you just change current = (current + 1) % posts.Length; to Mathf.PingPong(current + 1, posts.Length);
I'd go a bit like this:
float flipCooldown
float defaultFlipCooldown = 2.0f;
bool isGoingRight;
Vector2 pos1;
Vector2 pos2;
void Start() {
flipCooldown = defaultFlipCooldown;
isGoingRight = true;
pos1 = new Vector2(0, 0);
pos2 = new Vector2(5, 0); // whatever floats your boat
}
void Update()
{
Vector2 initialPosition = null;
Vector2 finalPosition = null;
if (flipCooldown <= 0) {
isGoingRight = !isGoingRight
flipCooldown = defaultFlipCooldown;
ChangeSprite();
}
if (isGoingRight) {
initialPos = pos1;
finalPos = pos2;
} else {
initialPos = pos2;
finalPos = pos1;
}
bird.transform.position = Vector3.Lerp (initialPos, finalPos, (Mathf.Abs(speed * Time.time) + 1.0f) / 2.0f);
flipCooldown -= Time.deltaTime;
}
What you want to get is that the Time.deltaTime is decreasing the cooldown for the bird to turn. You can easily change the cooldown in the defaultFlipCooldown variable. When it's done going one way, it'll just flip the position and the Lerp function will do the rest of the work. The ChangeSprite function will be just a GetComponent<SpriteRenderer>().sprite change.
If you don't want fix positions, you can calculate how much it'll fly, define the final position and just change the pos1 and pos2.
It's also important to note that WaitForSeconds will just work with Coroutines that is a concept for working with threads, never in a method like Update. You can learn more about Coroutines in Unity's manual: http://docs.unity3d.com/Manual/Coroutines.html

Unity 2D Rigidbody.velocity and transform.position causes random 'ghost' frame

I am creating a 2D platform / adventure game that uses flip screen to manage changing rooms.
My character moves using RigidBody.velocity, this works as I need it to, when my character reaches one of the screen's left or right extremes I use transform.position to move (effectively teleporting) the character to the other side of the screen, I then change the room. This gives the effect of moving to the next room along.
My flip screen code works fine, the changing room effect works without a problem, in fact almost everything works just as I like it, except that I get 1 frame where the character appears at a random point in between where the character moved from and where he moved to.
For example, my room is 16 tiles across, if my character moves left and passes x position '0' (the very left of the screen) I make a transform.position to x position 16 (keeping the y position constant) and then change rooms. I have logged the movement and what happens is (pseudo code)..
x < 0 (the change room code is run)
translate.position to x=16 (the far right)
x = 16 (this is correct)
The room changes
x = some float somewhere between 0 and 16 (this is NOT correct)
x = 16 (back to the correct position again)
This is my player code:
using UnityEngine;
using System.Collections;
public class MKManager : MonoBehaviour {
public float maxSpeed = 0.10f;
bool isFacingRight = false;
Rigidbody2D myBody;
bool grounded = true;
public static int liftdirection = 0;
void Start (){
myBody = GetComponent<Rigidbody2D> ();
}
void Update () {
checkRoomBounds ();
}
void FixedUpdate(){
float h = Input.GetAxisRaw ("Horizontal");
if (grounded) {
myBody.velocity = new Vector2 (h * maxSpeed, myBody.velocity.y);
if (h < 0) { //Moving Left
if (isFacingRight) {
FlipAnimation ();
}
} else if (h > 0) { //Moving Right
if (!isFacingRight) {
FlipAnimation ();
}
}
}
}
void checkRoomBounds(){
if (transform.position.x < 0) {
transform.position = new Vector3 (16.0f, transform.position.y, 0.0f);
GameManager.instance.moveRoom (-1);
} else if (transform.position.x > 16) {
transform.position = new Vector3 (0.0f, transform.position.y, 0.0f);
GameManager.instance.moveRoom (1);
}
}
void FlipAnimation(){
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
I have tried calling checkRoomBounds() in update, fixed update and lateupdate, all give the same result. If I do not call the moveRoom() function the same happens but the room is not changed, but the moveRoom() code is...
public void moveRoom(int direction){
if (room == 0) {
room = (10*currentFloor) + 1;
} else {
room += direction;
if (room == -1) {
room = 68;
} else if (room == 69) {
room = 0;
} else if (room % 10 == 9 || room % 10 == 0) {
//room += (direction * 2);
room = 0;
}
}
boardScript.SetupScene (room);
}
I've run out of ideas and don't know where I'm going wrong. Any help would be much appreciated.
Many thanks in advance

object movement as wave in Unity 3d

I created a object in unity
GameObject monsterclone =
(GameObject)Instantiate(monsterPrefab, floorPosition, Quaternion.identity);
This object should move in a wave style from a limit1 to limit2.
Then move back from limit2 to limit1.
Y position as well x position have to change in a specific way.
Vector3 nPos = mfloorPos + new Vector3(2f, 0f, 0f);
Vector3 oPos = mfloorPos + new Vector3(-2f, 0f, 0f);
How can I do it?
I can't exactly write the code without knowing more specific but i think this question is already asked any this link will help you out MOVE OBJECT as wave
EDIT:
I think the flat up and float down functionality will work for you for moving one point to another
example:
var floatup;
function Start(){
floatup = false;
}
function Update(){
if(floatup)
floatingup();
else if(!floatup)
floatingdown();
}
function floatingup(){
transform.position.y += 0.3 * Time.deltaTime;
yield WaitForSeconds(1);
floatup = false;
}
function floatingdown(){
transform.position.y -= 0.3 * Time.deltaTime;;
yield WaitForSeconds(1);
floatup = true;
}
example taken from
float amplitudeX = -25.0f;
float amplitudeY = 5.0f;
float omegaX = 0.5f;
float omegaY = 4.0f;
float index;
void Update () {
index += Time.deltaTime;
float x = amplitudeX*Mathf.Cos (omegaX*index);
float y = Mathf.Abs (amplitudeY*Mathf.Sin (omegaY*index));
if(transform.position.x > 24){
transform.eulerAngles = new Vector3(270, -90, 0);
}
if(transform.position.x < -24){
transform.eulerAngles = new Vector3(270, 90, 0);
}
transform.localPosition= new Vector3(x,y,20);
}
If this is a consitant wave and not dependant on speed I would use an animation to create a literal wave curve of the Position.Y value (much in the same principle as Ravindra Shekhawat has explained.) you can find out more about animation here.
Here is some code (untested) that you could go off. It is in c# so I hope it proves no issue with putting in to JavaScript.
bool monsterMoving = false;
void Update(){
//check monster moving to start updating position
if(monsterMoving == true){
//moving animation controls up and down "wave" movement
animation.CrossFade('moving');
//Lerp changes position
Transform.Lerp(transform.Position, oPos, Time.deltaTime);
if (transform.Position == oPos) {
//We are at destination, stop movement
monsterMoving = false;
}
} else {
// if monster stopped moving, return to idle animation (staying still)
animation.CrossFade('idle');
}
}
// function to send a new position to the monster object
void MoveTo(Vector3 newPos){
oPos = newPos;
monsterMoving = true;
}