2
\$\begingroup\$

Back again with a quick question! I have a few basic platforming mechanics going on in this scene. I have a prefab platform with an animation that loops back and forth between two different x positions, but does not begin looping until OnCollisionStay2D activates with my player object with the tag "Red cube".

But once the animation starts the red cube has very little friction with the platform and falls off. I have attempted to fix this AddRelativeForce in this script. Is there any way to increase the friction to where my player cube isn't slipping off? Or is there anyway to script my platform to add constant force to my player where I will move with platform seamlessly? Thank you so much for your time! You guys are a great help :)

using UnityEngine;
using System.Collections;


public class PlatformMovement : MonoBehaviour {

    public Rigidbody2D rb;
    public float speed;

    void Start()
    {
        rb = GameObject.FindGameObjectWithTag ("Red Cube").GetComponent<Rigidbody2D> ();
    }

    void OnCollisionEnter2D(Collision2D coll) 
    {
        if (coll.gameObject.tag == "Red Cube") 
        {
            Debug.Log ("Something has entered this zone.");
            GetComponent<Animation> ().Play ("Side To Side");
        }
    }

    void OnCollisionStay2D(Collision2D coll) 
    {
        if (coll.gameObject.tag == "Red Cube") 
        {
            rb.AddRelativeForce(new Vector2(speed, 0), ForceMode2D.Force);
        }

    }

    }
\$\endgroup\$
1
\$\begingroup\$

Try creating a physics material and adding it to your object and then in your code write the code below whenever you want to change the friction:

collider2D.material.dynamicFriction = YOUR VALUE HERE; collider2D.material.staticFriction = YOUR VALUE HERE;

(Dynamic friction is the friction while object moves and static is hen it isn't moving)

Make sure you have rigidbody on your game object.

You can find more on physics material here: http://docs.unity3d.com/Manual/class-PhysicMaterial.html

\$\endgroup\$
  • \$\begingroup\$ would you mind providing an example in code? I am getting errors with the code. collider2D.material.dynamicFriction = 1; collider2D.material.staticFriction = 1; \$\endgroup\$ – Ham Jul 30 '15 at 15:25
  • \$\begingroup\$ Could you post the error? \$\endgroup\$ – Vadim Tatarnikov Jul 31 '15 at 11:18
  • \$\begingroup\$ I guess something might have changed in the new version so try this instead. ` GetComponent<Collider2D> ().sharedMaterial.friction = VALUE FROM 0 TO 1 (FLOAT); ` \$\endgroup\$ – Vadim Tatarnikov Jul 31 '15 at 12:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.