# Cocos Intrinsic ads Integration

{% file src="/files/D58uwfkzf5LzGwDrYBJ8" %}

## Intrinsic Ads WebSDK Integration Guide for Cocos Creator

### Table of Contents

1. Overview
2. Prerequisites
3. Installation
4. Quick Start
5. SDK Initialization
6. Adding Ads to Your Game
7. Configuration Reference
8. Advanced Features
9. Best Practices
10. Troubleshooting
11. API Reference

***

### Overview

The Anzu WebSDK Adapter enables seamless integration of dynamic and static in-game advertisements into Cocos Creator projects. This adapter bridges the Anzu WebSDK with Cocos Creator's component system, providing a simple drag-and-drop interface for displaying ads in both 2D and 3D games.

**Key Features:**

* Support for both 2D sprites and 3D mesh rendering
* Dynamic (rotating) and static ad channels
* Image and video ad support with audio control
* Automatic viewability and visibility tracking
* GDPR and COPPA compliance built-in
* Debug statistics overlay
* Click/interaction tracking

**Version Compatibility:**

* Adapter Version: 1.2.1
* Tested with Cocos Creator 2.3
* Likely compatible with Cocos Creator 2.x and 3.x versions

***

### Prerequisites

Before integrating the Anzu WebSDK, ensure you have:

1. **Cocos Creator** installed (version 2.3 or later recommended)
2. **Anzu App Key** from the Playgama Developer Success Team
3. **Basic knowledge** of Cocos Creator's component system
4. **HTML5 export target** (required for WebSDK functionality)

***

### Installation

#### Step 1: Copy SDK Files

1. Locate the `anzuSDK` folder in this package
2. Copy the entire `anzuSDK` folder into your Cocos Creator project's `assets` directory

Your project structure should look like:

```
your-project/
├── assets/
│   ├── anzuSDK/
│   │   ├── adapter/
│   │   │   ├── components/
│   │   │   └── utilities/
│   └── [your other assets]
```

#### Step 2: Verify Import

1. Open your Cocos Creator project
2. In the **Assets Panel**, expand the `anzuSDK` folder
3. Verify that all scripts are imported without errors
4. Check the **Console** for any import warnings

***

### Quick Start

#### 5-Minute Integration

Follow these steps to get ads running in your game:

**1. Initialize the SDK**

1. Create a new **empty node** in your main scene hierarchy (or use an existing persistent node)
2. Rename it to `AnzuSDK` (optional, for organization)
3. In the **Properties Panel**, click **Add Component**
4. Navigate to **AnzuSDK** → **common** → **AnzuSDK**
5. In the component properties, enter your **App Key** from Anzu Dashboard

**2. Add an Ad Display**

**For 3D Games:**

1. Create a new **3D Node** → **Cube** (or use existing geometry)
2. Ensure the node has a **MeshRenderer** component with a **Quad** primitive
3. Add **AnzuSDK** → **anzuAd** → **AnzuAd** component
4. Configure the component:
   * **Channel Name**: `billboard-01` (or any unique name)
   * **Aspect Ratio**: `1.778` (16:9) or your preferred ratio
   * **Is Dynamic**: `true` (for rotating ads) or `false` (static)

**For 2D Games:**

1. Create a new **2D Node** → **Sprite**
2. Add **AnzuSDK** → **anzuAd** → **AnzuAd** component
3. Configure the same properties as above

**3. Run and Test**

1. Build and run your project in **HTML5 mode**
2. The ad should load and display automatically
3. Check the browser console for SDK initialization logs

***

### SDK Initialization

#### AnzuSDK Component

The `AnzuSDK` component is the entry point for the entire SDK and must be present in your scene before any ads can be displayed.

**Recommended Setup:**

* Attach to a **persistent node** (use `cc.game.addPersistRootNode(this.node)` if needed)
* Initialize **only once** per application session
* Place in the **first scene** that loads in your game

#### Configuration Properties

| Property              | Type    | Default | Description                                                 |
| --------------------- | ------- | ------- | ----------------------------------------------------------- |
| **appKey**            | String  | ""      | Your Anzu App Key from the Dashboard (required)             |
| **logLevel**          | Number  | 1       | Logging verbosity: 0=Debug, 1=Info, 2=Warn, 3=Error, 4=None |
| **gdprConsentStatus** | Number  | -1      | GDPR consent: -1=unknown, 0=no consent, 1=consent           |
| **gdprConsentString** | String  | ""      | IAB TCF consent string (if applicable)                      |
| **isCoppaRegulated**  | Boolean | false   | Set to true if your app is subject to COPPA regulations     |

#### Example: Basic Initialization

```javascript
// Attach this to the same node as AnzuSDK component
cc.Class({
    extends: cc.Component,

    onLoad() {
        // Make this node persistent across scenes
        cc.game.addPersistRootNode(this.node);

        // The AnzuSDK component will automatically initialize
        // You can verify initialization status:
        this.scheduleOnce(() => {
            const AnzuCore = require('AnzuCore');
            if (AnzuCore.isInitialized()) {
                cc.log('Anzu SDK is ready!');
            }
        }, 0.5);
    }
});
```

#### GDPR Compliance Example

```javascript
onLoad() {
    const anzuSDK = this.node.getComponent('AnzuSDK');

    // Assume you have a consent management system
    getUserConsent((hasConsent, consentString) => {
        anzuSDK.gdprConsentStatus = hasConsent ? 1 : 0;
        anzuSDK.gdprConsentString = consentString || "";

        // SDK will use these values on next initialization
    });
}
```

***

### Adding Ads to Your Game

#### AnzuAd Component

The `AnzuAd` component handles all ad rendering and measurement. It supports both 2D and 3D rendering automatically based on the node's components.

#### 3D Ad Integration (MeshRenderer)

**Requirements:**

* Node must have `cc.MeshRenderer` component
* Mesh must be a **Quad** primitive (plane)
* Material can be any material (will be updated automatically)

**Setup Steps:**

1. **Create the 3D Ad Node:**

   ```
   Scene Hierarchy:
   └── BillboardAd (Node)
       ├── MeshRenderer (Quad, any material)
       └── AnzuAd (Component)
   ```
2. **Configure AnzuAd Component:**
   * **Channel Name**: Unique identifier (e.g., `wall-ad-left`)
   * **Aspect Ratio**: Match your ad surface (16:9 = 1.778, 1:1 = 1.0)
   * **Is Dynamic**: `true` for rotating ads
   * **Is Clickable**: `true` to enable click interactions
   * **Shrink To Fit**: `true` to preserve original node size
3. **Position and Scale:**
   * Position the node where you want the ad to appear
   * Scale it to the desired size in world units
   * The ad texture will automatically match the aspect ratio

#### 2D Ad Integration (Sprite)

**Requirements:**

* Node must have `cc.Sprite` component
* Canvas mode must be enabled (default for 2D games)

**Setup Steps:**

1. **Create the 2D Ad Node:**

   ```
   Scene Hierarchy:
   └── BannerAd (Node)
       ├── Sprite (empty spriteFrame is OK)
       └── AnzuAd (Component)
   ```
2. **Configure AnzuAd Component:**
   * Same properties as 3D setup above
3. **Size and Position:**
   * Set the sprite's `width` and `height`
   * The ad will scale to fill these dimensions

#### Multiple Ads in One Scene

You can have multiple ad instances:

```
Scene Hierarchy:
└── Ads (Node)
    ├── Billboard_01 (AnzuAd: "billboard-01")
    ├── Billboard_02 (AnzuAd: "billboard-02")
    ├── Poster_01 (AnzuAd: "poster-01")
    └── Banner_UI (AnzuAd: "banner-ui")
```

**Important:** Each ad must have a **unique channel name**.

***

### Configuration Reference

#### AnzuAd Component Properties

| Property        | Type    | Default | Description                                                                              |
| --------------- | ------- | ------- | ---------------------------------------------------------------------------------------- |
| **channelName** | String  | ""      | Unique channel identifier. Leave empty for auto-generation.                              |
| **aspectRatio** | Number  | 1.778   | Aspect ratio of ad content (width/height). Common values: 16:9=1.778, 4:3=1.333, 1:1=1.0 |
| **isDynamic**   | Boolean | true    | `true`: Rotating ads (updates). `false`: Static ad (single impression)                   |
| **isClickable** | Boolean | true    | Enable click/tap interaction tracking                                                    |
| **shrinkToFit** | Boolean | true    | Scale ad to preserve original node dimensions                                            |
| **allowImage**  | Boolean | true    | Allow image-based ads                                                                    |
| **allowVideo**  | Boolean | true    | Allow video-based ads                                                                    |
| **allowAudio**  | Boolean | false   | Allow video ads with audio (requires user interaction)                                   |

#### Aspect Ratio Guide

Choose the aspect ratio that matches your ad surface:

| Ratio | Decimal | Use Case                       |
| ----- | ------- | ------------------------------ |
| 16:9  | 1.778   | Widescreen billboards, banners |
| 4:3   | 1.333   | Traditional displays           |
| 1:1   | 1.0     | Square posters, tiles          |
| 21:9  | 2.333   | Ultra-wide banners             |
| 9:16  | 0.5625  | Vertical/portrait displays     |

#### Channel Types

**Dynamic Channels (`isDynamic: true`):**

* Ads rotate/update automatically
* Multiple impressions per session
* Best for prominent placements
* Higher revenue potential

**Static Channels (`isDynamic: false`):**

* Single ad per session
* Useful for background/ambient ads
* Lower performance overhead

***

### Advanced Features

#### Debug Statistics Overlay

The `AnzuStats` component displays real-time debug information for any ad.

**Setup:**

1. Select an existing node with `AnzuAd` component
2. Add **AnzuSDK** → **anzuAd** → **AnzuStats** component
3. Run the game

**Displayed Information:**

* Node name and state
* Viewing angle (degrees)
* Visibility percentage
* Channel name and type
* Impression count
* Empty impressions (failed loads)

**Example:**

```
Scene Hierarchy:
└── Billboard_01
    ├── AnzuAd
    └── AnzuStats  ← Add this for debugging
```

#### Click Interaction

Ads automatically track clicks when `isClickable` is enabled. To manually trigger interactions:

```javascript
// Get the AnzuAd component
const anzuAd = this.node.getComponent('AnzuAd');

// Trigger interaction (e.g., on custom button press)
if (anzuAd) {
    anzuAd.interact();
}
```

#### Getting Ad Metrics

You can query ad performance metrics in code:

```javascript
const anzuAd = this.node.getComponent('AnzuAd');

// Viewing angle (0-90 degrees)
const angle = anzuAd.getAngle();

// Visibility (0.0 to 1.0, percentage of ad on screen)
const visibility = anzuAd.getVisibility();

// Viewability score (combines angle and visibility)
const viewability = anzuAd.getViewability();

// Channel information
const channelName = anzuAd.getChannelName();
const channelType = anzuAd.getChannelType(); // "dynamic" or "static"
const impressions = anzuAd.getChannelImpressions();
const empties = anzuAd.getChannelEmpties();

cc.log(`Ad '${channelName}' viewability: ${viewability.toFixed(2)}`);
```

#### Custom Camera Selection

By default, the SDK automatically detects the active camera. To override:

```javascript
const AnzuView = require('AnzuView');

// Use a specific camera for all ad measurements
const myCamera = this.node.getComponent(cc.Camera);
AnzuView.setManualCamera(myCamera);

// Reset to automatic detection
AnzuView.resetManualCamera();
```

#### ILRD (Impression-Level Revenue Data)

To receive ILRD callbacks via URI schema:

```javascript
const UriSchema = require('UriSchema');

// Register a custom URI schema handler
UriSchema.registerHook('myapp', (data) => {
    cc.log('ILRD Data:', data);
    // Process revenue data
});
```

#### Content Filtering

Control which ad types are allowed:

```javascript
const anzuAd = this.node.getComponent('AnzuAd');

// Only allow image ads
anzuAd.allowImage = true;
anzuAd.allowVideo = false;
anzuAd.allowAudio = false;

// Only allow silent videos
anzuAd.allowVideo = true;
anzuAd.allowAudio = false;
```

***

### Best Practices

#### Performance Optimization

1. **Limit Active Channels:**
   * Use 3-5 dynamic channels per scene maximum
   * Use static channels for background ads
   * Disable ads that are far from the player
2. **Texture Resolution:**
   * Ads are rendered to canvas textures
   * Larger ad surfaces may impact performance
   * Consider reducing `aspectRatio` precision if needed
3. **Update Frequency:**
   * SDK updates every frame via `AnzuSDK.update(dt)`
   * Viewability is calculated only when requested by WebSDK
   * Minimal overhead when ads are not visible

#### Ad Placement Strategy

1. **Visibility:**
   * Place ads where players naturally look
   * Avoid placing ads in high-speed areas
   * Ensure adequate lighting on ad surfaces
2. **Size and Distance:**
   * Larger ads work better at greater distances
   * Smaller ads for close-up views
   * Aspect ratio should match surface shape
3. **Quantity:**
   * Quality over quantity
   * Too many ads can overwhelm players
   * Strategic placement yields better metrics

#### Scene Management

1. **Persistent SDK:**

   ```javascript
   // In your main/loading scene, on the AnzuSDK node:
   cc.game.addPersistRootNode(this.node);
   ```
2. **Clean Scene Transitions:**
   * AnzuAd components automatically unregister on disable
   * No manual cleanup required
   * SDK persists across scene loads
3. **Dynamic Loading:**

   ```javascript
   // Load ad nodes dynamically
   cc.loader.loadRes('prefabs/BillboardAd', (err, prefab) => {
       const adNode = cc.instantiate(prefab);
       adNode.parent = this.adContainer;
       // AnzuAd will auto-initialize on enable
   });
   ```

#### Testing and Debugging

1. **Enable Debug Logging:**
   * Set `AnzuSDK.logLevel` to `0` (Debug) during development
   * Set to `3` (Error) or `4` (None) for production
2. **Use AnzuStats:**
   * Attach to all ads during development
   * Verify viewability metrics
   * Monitor impression counts
3. **Browser Console:**
   * Check for SDK initialization messages
   * Look for channel registration logs
   * Monitor WebSDK update calls
4. **Test Different Scenarios:**
   * Test with GDPR consent enabled/disabled
   * Test with COPPA enabled
   * Test with different network speeds
   * Test ad blocking software compatibility

***

### Troubleshooting

#### Common Issues

**1. Ads Not Displaying**

**Symptoms:** Ad nodes are visible but show no content

**Solutions:**

* Verify `AnzuSDK` component is initialized (check console logs)
* Ensure valid `appKey` is set in AnzuSDK component
* Check that node has correct renderer (MeshRenderer or Sprite)
* For MeshRenderer, verify mesh is Quad primitive
* Enable debug logging (`logLevel: 0`) to see detailed errors

**2. "AnzuSDK not initialized" Error**

**Symptoms:** Console error when ads try to load

**Solutions:**

* Ensure `AnzuSDK` component is in the scene
* Verify SDK initialization happens before ad components
* Add a delay before enabling ad nodes:

  ```javascript
  this.scheduleOnce(() => {
      this.adNode.active = true;
  }, 1.0); // Wait 1 second for SDK init
  ```

**3. Black or Empty Textures**

**Symptoms:** Ad appears as black rectangle

**Solutions:**

* Check browser console for CORS errors
* Verify HTML5 canvas support in target browser
* Ensure WebSDK loaded successfully (check Network tab)
* Try disabling video ads: `allowVideo: false`

**4. Incorrect Ad Dimensions**

**Symptoms:** Ad is stretched or cropped

**Solutions:**

* Verify `aspectRatio` matches your desired ratio
* Enable `shrinkToFit` to preserve original node size
* Check node dimensions and scale
* For sprites, ensure width/height are set

**5. No Impressions Tracked**

**Symptoms:** `getChannelImpressions()` returns 0

**Solutions:**

* Verify ad is visible on screen
* Check viewing angle is reasonable (< 70 degrees)
* Ensure camera is active and positioned correctly
* Check `getVisibility()` and `getViewability()` values
* Ads must meet viewability threshold to count impressions

**6. Clicks Not Registering**

**Symptoms:** Tapping/clicking ads doesn't work

**Solutions:**

* Ensure `isClickable` is set to `true`
* Verify you're calling `anzuAd.interact()` on click
* Check that ad has active content (not empty)
* For touch input, ensure click event reaches the ad node

#### WebSDK Loading Issues

If the Anzu WebSDK fails to load:

1. **Check Internet Connection:**
   * WebSDK loads from external CDN
   * Requires active internet during development
2. **Verify Script Loading:**

   ```javascript
   // Check if WebSDK is loaded
   if (window.Anzu) {
       cc.log('WebSDK loaded successfully');
   } else {
       cc.error('WebSDK failed to load');
   }
   ```
3. **Firewall/Ad Blocker:**
   * Disable ad blocking extensions during development
   * Check firewall settings

#### Getting Help

If issues persist:

1. **Check Console Logs:**
   * Set `logLevel: 0` for maximum verbosity
   * Look for specific error messages
2. **Contact Anzu Support:**
   * Visit [Anzu Dashboard](https://console.anzu.io)
   * Provide App Key and error logs
   * Include browser/platform information

***

### API Reference

#### AnzuSDK Component

**File:** `anzuSDK/adapter/components/common/AnzuSDK.js`

**Properties:**

* `appKey: String` - Anzu App Key (required)
* `logLevel: Number` - Logging level (0-4)
* `gdprConsentStatus: Number` - GDPR consent status
* `gdprConsentString: String` - IAB TCF consent string
* `isCoppaRegulated: Boolean` - COPPA compliance flag

**Lifecycle:**

* `onLoad()` - Initializes SDK
* `update(dt)` - Updates SDK every frame

#### AnzuAd Component

**File:** `anzuSDK/adapter/components/anzuAd/AnzuAd.js`

**Properties:**

* `channelName: String` - Unique channel identifier
* `aspectRatio: Number` - Ad aspect ratio (width/height)
* `isDynamic: Boolean` - Dynamic (true) or static (false) channel
* `isClickable: Boolean` - Enable click tracking
* `shrinkToFit: Boolean` - Preserve original node size
* `allowImage: Boolean` - Allow image ads
* `allowVideo: Boolean` - Allow video ads
* `allowAudio: Boolean` - Allow audio in video ads

**Methods:**

* `interact()` - Trigger click interaction
* `getAngle(): Number` - Get viewing angle (0-90 degrees)
* `getVisibility(): Number` - Get visibility (0.0-1.0)
* `getViewability(): Number` - Get viewability score (0.0-1.0)
* `getChannelName(): String` - Get channel name
* `getChannelType(): String` - Get channel type ("dynamic" or "static")
* `getChannelImpressions(): Number` - Get impression count
* `getChannelEmpties(): Number` - Get empty impression count

#### AnzuStats Component

**File:** `anzuSDK/adapter/components/anzuAd/AnzuStats.js`

**Properties:**

* (No configurable properties)

**Requirements:**

* Must be attached to node with AnzuAd component

#### AnzuCore Utility

**File:** `anzuSDK/adapter/utilities/AnzuCore.js`

**Static Methods:**

* `initialize(appSettings)` - Initialize SDK with settings
* `update(deltaTime)` - Update SDK (called by AnzuSDK component)
* `isInitialized(): Boolean` - Check if SDK is ready

#### AnzuView Utility

**File:** `anzuSDK/adapter/utilities/AnzuView.js`

**Static Methods:**

* `getCamera(): cc.Camera` - Get active camera
* `setManualCamera(camera)` - Override camera selection
* `resetManualCamera()` - Reset to automatic detection
* `worldToScreen(worldPos): cc.Vec2` - Convert world to screen coordinates
* `screenToWorld(screenPos): cc.Vec3` - Convert screen to world coordinates
* `getRay(screenPos): cc.geomUtils.Ray` - Get ray from screen position
* `getScreenBoundsPolygon(): Array` - Get screen boundary polygon

#### UriSchema Utility

**File:** `anzuSDK/adapter/utilities/UriSchema.js`

**Static Methods:**

* `registerHook(schema, callback)` - Register URI schema handler
  * `schema: String` - URI schema name (e.g., "myapp")
  * `callback: Function` - Handler function receiving data

***

### Changelog

#### Version 1.2.1

* Initial release with Cocos Creator 2.3 support
* 3D mesh and 2D sprite rendering
* Dynamic and static ad channels
* GDPR and COPPA compliance
* Debug statistics overlay
* Viewability tracking


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wiki.playgama.com/playgama/intrinsic-in-game-ads/cocos-intrinsic-ads-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
