Search code examples
unity-game-enginecinemachine

How do you fire off the Cinemachine Impulse source without using the Collision one?


How do properly call GenerateImpulse() to implement Cinemachine's camera ImpulseListener (camera shake) via the ImpulseSource? I can get it working if I put a CollisionImpuleSource on the player, but I don't want that. I want to use the Impulse Source and then with code, determine when to shake.

I'm looking at the documentation https://docs.unity3d.com/Packages/[email protected]/manual/CinemachineImpulseSource.html but not seeing how to properly make the ImpulseSource fire off.

I set a private...

public CinemachineVirtualCamera vCamera;
private CinemachineImpulseSource  _impulseSource;

I can call the generateImpulse...

_impulseSource.GenerateImpulse();

but I don't see how to get the component

private void Start(){

_impulseSource = vCamera.GetCinemachineComponent<CinemachineImpulseSource>();

}

I get an error..

The type 'Cinemachine.CinemachineImpulseSource' must be convertible to 'Cinemachine.CinemachineComponentBase' in order to use it as parameter 'T' in the generic method 'T Cinemachine.CinemachineVirtualCamera.GetCinemachineComponent()'

but if I change the private too..

private CinemachineComponentBase  _impulseSource;

that doesn't help. Need some guidance on how this should be referenced.


Solution

  • Think of the CinemachineImpulseSource as a component on a custom GameObject.

    Attach the CinemachineImpulseSource Script Component to a new gameobject. You could probably add it to the same GO where the script from your question is attached to, did not test this though. Configure the impulse source component according to your needs and reference it. If its on the same GameObject, create a public field just as with your camera reference and assign it in the inspector or get it using GetComponent<CinemachineImpulseSource>(). Then you can call GenerateImpulse() on it.

    public CinemachineVirtualCamera vCamera;
    public CinemachineImpulseSource  ImpulseSource; // Assign in inspector
    
    ...
    
    ImpulseSource.GenerateImpulse();