3

I want to restrict player movement in the sphere, the schematic diagram show as below. If player movement is out of range, then restrict player to sphere max radius range.

How can I write C# code to implement it, like this?

The player is at the center of a circle with a radius of 0.5. Anything beyond the circumference of the circle is out of bounds.

These are my current steps:

  1. Create 3D sphere

  2. Create C# code append to sphere object

My code so far:

public Transform player;

void update(){
      Vector3 pos = player.position;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Was your problem solved? If so, please consider selecting a posted answer as the right one. – Kardux Mar 13 '17 at 13:08

2 Answers2

3

I don't know how you calculate your player`s position but before assigning the new position to the player you should check and see if the move is eligible by checking the new position distance form the center of the sphere

//so calculate your player`s position 
//before moving it then assign it to a variable named NewPosition
//then we check and see if we can make this move then we make it
//this way you don't have to make your player suddenly stop or move it 
//back to the bounds manually          

if( Vector3.Distance(sphereGameObject.transform.position, NewPosition)< radius)
{
 //player is in bounds and clear to move
 SetThePlayerNewPosition();
}
Milad Qasemi
  • 3,011
  • 3
  • 13
  • 17
1

What @Milad suggested is right but also include the fact you won't be able to "slide" on the sphere border if your movement vector even slightly goes outside the sphere :

Sphere vector explanation

(sorry for the crappy graphic skills...)

What you can do if you want to be able to "slide" on the sphere interior surface is get the angle formed between the player position and the X vector and then apply this angle with the :

public Transform player;
public float sphereRadius;

void LateUpdate()
{
    Vector3 pos = player.position;
    float angle = Mathf.Atan2(pos.y, pos.x);
    float distance = Mathf.Clamp(pos.magnitude, 0.0f, sphereRadius);
    pos.x = Mathf.Cos(angle) * distance;
    pos.y = Mathf.Sin(angle) * distance;
    player.position = pos;
}

Just make sure using this won't counter effect your player movement script (that's why I put it in LateUpdate() in my example).

Kardux
  • 2,117
  • 1
  • 18
  • 20