I have a hollow cylinder, within which is a sphere. The forward vector is predefined, so the user can not change their forward speed. What they do have control of, however, is the rotation of the sphere around the cylinder by swiping the screen.

enter image description here

Again, I want this rotational movement to occur while the ball is traveling on a forward vector.

Here is the code I have thus far in C#:

public float speed;

private Rigidbody rb;

void Start()
    rb = GetComponent<Rigidbody>();

void FixedUpdate()
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = 1;


    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);

The current controls are for the left and right arrow keys, but I will implement swiping later.

I would appreciate any help you could provide. Thank you.

  • \$\begingroup\$ Create a parent object centered in the cylinder. Make the sphere a child of that parent. Rotate the parent and the sphere will "orbit" the parent origin. \$\endgroup\$
    – House
    Jun 13 '18 at 21:39
  • \$\begingroup\$ gamedev.stackexchange.com/questions/61981/… \$\endgroup\$
    – House
    Jun 13 '18 at 21:39

If you want to do it purely from a mathematical point of view (so it works outside Unity too) you can use this:

x = sin(rot) *rad;
y = cos(rot) *rad;

This assumes that rot is the rotation of the sphere inside the pipe. This should be in radians, so to convert from 90 degrees do something like rot = 90 *Math.PI /180.

It also assumes that the sphere's z axis is the one moving "forward", which is unaffected.

This lets you have complete control over the sphere, you can for example reduce rad if you pan to make the sphere "jump" (approach the center) or increase/decrease it in case you plan to make the pipe bigger/smaller while the sphere is still inside.

  • \$\begingroup\$ Thank you. So would the rot value come from the user's finger swiping on the screen? \$\endgroup\$
    – user117136
    Jun 13 '18 at 23:44
  • \$\begingroup\$ @JamieCorkhill This depends on how you want your game to function. You can configure it like "every 10 pixels the finger moves to the right, rot increases by 1 degree", same with the left side, this will cause the sphere to move to either direction as you are swiping. \$\endgroup\$
    – TomTsagk
    Jun 14 '18 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy