Hi guys
This is my first time making a game so forgive me if I’m asking really easy questions. I’ve put together the basics of a top down 2d scrolling game for mobile devices. I’de like the player to be able to move in the centre of the phone but the sides are going to have walls for a background so moving in those areas would look really weird. I’ve tried adding cubes with box colliders but the character just pushes them out of the way or goes straight through I’m sure I’m missing something in the code and would really appreciate some help with this one.
Thanks
this is the code I’m using to move the character:
function Update()
{
if(Input.GetMouseButton(0))
{
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, rayCastHit))
{
transform.position.x = rayCastHit.point.x;
}
}
}
2 Answers
2
I had the same problem when working in 3D. Are you moving your character with a rigidbody? If so, try to use alternate means for it, such as a standard character controller.
And you can use RayCasting with layersmasks.
I.e “int wallLayer = 1 << 9” declare the 9th layer in the layer list. Then you have to invert the mask to only trigger on the 9th layer:
wallLayer = ~wallLayer
Then in you use your rayCast with your wallLayer as your layermask
Hello,
If i undertood what do you want, invisible walls, when your player hit them he stop right?
First you will need your player to have Colider2D, same as the walls
For a player to able to move those invisible walls, means that they have RigidBody
- Set walls “Mass” to 999, so they can be very heavy
- Set walls Gravity to 0, so they wont fall down
- Set player “Mass” to 0.01, so he cant push nothing, he will be very light
- Set walls Gravity to 0, so he wont fall down
- To turn them invisible just remove Sprite Renderer
- To give them Colider Shape, you can use BoxCollider2D and change size, you will see some green line
I hope i helped from what i undertood, good luck have a nice day
You can disable or remove the mesh renderer component to make it invisible. If the character is pushing the cube it is likely because you need to check Is Trigger to true in your collider.
– emisaurI checked 'is Trigger' and unchecked 'Mesh Renderer' on the inspector of the cube but the character just goes straight through it :/ any other suggestions?
– jonhayward88You'll have to attach a script which uses OnTriggerEnter and then stops the character from moving into it. I highly recommend watching the tutorial projects on the Unity site which covers this
– emisaurthanks will do if i make any progress ill get back to you thanks again for your help
– jonhayward88I read a little about OnTriggerEnter and I started thinking about how I could implement it in my code and I got thinking about the raycast part of the code do you know if there is any way to kind of constrain where rays can go?
– jonhayward88